2017-02-28 107 views
1

我想基于Boostrap构建一类自定义警报。一切都还很年轻,但我遇到了一个问题。只有发生点击事件时,我如何才能根据点击的按钮返回值?在这里你可以看到我是如何设置的值(很容易,做检查)来自类函数的返回值

$modal.on('click', '[data-alertify="cancel"]', function(){ 
     var value = 'no'; 
     $modal.modal('hide'); 
     return value; 
    }); 
    $modal.on('click', '[data-alertify="confirm"]', function(){ 
     var value = 'yes'; 
     $modal.modal('hide'); 
     return value; 
    }); 

这里是我的类和测试代码JSFiddle

正如你可以看到,出现警告(显然)之前的模式是所示。我该如何处理?我如何等待正确的值被返回,然后提醒它?

回答

2

问题是这些回调函数是异步调用的,其中的return语句返回的值在以后不能使用。如果整个过程是同步下面的结构只会工作:

var ret = Alertify.alert({ 
    content: 'This is MY alert content!' 
}); 

...但Alertify.alert()不会返回所需的值,因为用户还未点击。这个alert()函数不会返回任何东西,并且肯定不会返回仍然必须发生的点击结果。

此场景对于引入承诺是理想的。这是它的外观,当你做到这一点:

首先改变showModal函数返回一个承诺:

var showModal = function (alert_id) { 
    $('body').append($html); 
    var $modal = $('#' + alert_id); 
    $modal.modal('show'); 
    var dfd = $.Deferred(); // create a promise 
    $modal.on('click', '[data-alertify="cancel"]', function(){ 
    var value = 'no'; 
    $modal.modal('hide'); 
    dfd.resolve(value); // instead of returning the value, resolve the promise with it 
    }); 
    $modal.on('click', '[data-alertify="confirm"]', function(){ 
    var value = 'yes'; 
    $modal.modal('hide'); 
    dfd.resolve(value); 
    }); 
    $modal.on('hidden.bs.modal', function(){ 
    $(this).remove(); 
    dfd.resolve(); 
    }); 
    return dfd.promise(); // return the (unresolved) promise 
}; 

现在Alertify.alert会返回一个承诺对象,它公开了一个then方法,给你传递回拨:

Alertify.alert({ 
    content: 'This is MY alert content!' 
}).then(function(ret) { 
    alert(ret); 
}); 

......就是这样。

这里是更新的fiddle

+0

为什么“on”回调异步调用? – KAD

+0

因为它们是由用户点击触发的,而这发生在代码已经完成运行时。 – trincot

+0

我知道我必须处理承诺,我只是在猜测是否有另一种方式。是否有可能将该值返回给变量,而不使用'$ .then()'?例如'var ret_value = Alertify.prompt(.....);'以便我的代码看起来更干净? – Yuri