问题是这些回调函数是异步调用的,其中的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。
为什么“on”回调异步调用? – KAD
因为它们是由用户点击触发的,而这发生在代码已经完成运行时。 – trincot
我知道我必须处理承诺,我只是在猜测是否有另一种方式。是否有可能将该值返回给变量,而不使用'$ .then()'?例如'var ret_value = Alertify.prompt(.....);'以便我的代码看起来更干净? – Yuri