如何使用$.When用于回调函数
How to use $.when for a callback function?
我想说,当这个函数close()完成时,运行这个函数init()。但这对我不起作用。
$.when(close(toolTip)).done(init(toolTip, anchor));
我没有使用$。当任何ajax相关的,只是试图确保close()完成之前,我调用init(),不,我不能坚持init()在close()结束。什么好主意吗?
这里是close()
var close = function (toolTip) {
toolTip.fadeOut('fast', function (e) {
if (typeof e !== 'undefined') {
//Re-set values applied when initted
var toolTipBd = toolTip.find('.bd:first');
toolTip.css('width', '');
toolTipBd.css('max-height', '');
toolTip.css('max-height', '');
toolTipBd.css('overflowY', '');
}
});
};
您的close()
实现应该是这样的:
var close = function (toolTip) {
var d = $.Deferred();
toolTip.fadeOut('fast', function (e) {
if (typeof e !== 'undefined') {
//Re-set values applied when initted
var toolTipBd = toolTip.find('.bd:first');
toolTip.css('width', '');
toolTipBd.css('max-height', '');
toolTip.css('max-height', '');
toolTipBd.css('overflowY', '');
}
d.resolve();
});
return d.promise();
};
$.when
与Deferred
一起工作,它返回一个新的Deferred
,当您提供的所有Deferred
都解决时,它将解决。
由于close()
似乎没有返回承诺,when
将立即解决(根据when()
的文档)。
但是,如果close()
是同步的,则根本不需要when()
。如果它是异步的,你需要返回一个Promise
,并在你的动画或其他东西完成时解决它;
function close(what) {
var promise = jQuery.Deferred();
what.fadeOut('slow', function () {
promise.resolve();
});
return promise.promise();
}
…但是您仍然不需要$.when
,因为只涉及1 promise。$.when
只在有多个承诺时有用。
close(toolTip).done(function () {
init(toolTip, anchor);
});
还注意done(init(tooltip, anchor))
将立即调用init
,并将该函数调用的结果传递给done()
;相反,您需要传递一个函数给done。由于init
需要参数,我们通过引入一个匿名函数来解决这个问题。如果init
不需要任何参数,它就像这样简单:
close(toolTip).done(init);
返回toolTip:
return toolTip.fadeOut(...
如果由于某种原因选择了多个元素,则使用回调来解析延迟对象可能会导致奇怪的结果。
这是有效的,因为jQuery对象有一个.promise
方法,当调用时,返回一个承诺对象,当所有活动动画完成。$.when
对所有传入参数调用.promise
。
您还需要以不同的方式调用init,例如
$.when(close(toolTip)).done(function(){
init(toolTip, anchor);
});
并且,正如其他人指出的那样,你可以将其缩短为
close(toolTip).promise().done(function(){
init(toolTip, anchor);
});
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定