jQuery - 具有自定义回调的函数
我试图在某些进程完成执行后执行特定的函数。
我的具体示例引用了许多 animate() 方法,之后我想调用另一个函数,但是只有在 animate() 方法完成处理后才应调用该函数:
var testObject = {
methodOne : function(callbackMethod) {
$('#item').animate({ 'paddingLeft' : '20px'}, { duration: 200, queue: false });
$('#item2').animate({ 'paddingLeft' : '30px'}, { duration: 200, queue: false });
$('#item3').animate({ 'paddingLeft' : '40px'}, { duration: 200, queue: false });
testObject.callbackMethod();
},
run : function() {
alert('done');
}
};
$(function() {
testObject.methodOne(run);
});
知道如何实现此目的吗?
I'm trying to execute a specific function once some processes finished executing.
My specific example refers to a number of animate() methods after which I want to call another function, however this function should only be called once the animate() methods finished processing:
var testObject = {
methodOne : function(callbackMethod) {
$('#item').animate({ 'paddingLeft' : '20px'}, { duration: 200, queue: false });
$('#item2').animate({ 'paddingLeft' : '30px'}, { duration: 200, queue: false });
$('#item3').animate({ 'paddingLeft' : '40px'}, { duration: 200, queue: false });
testObject.callbackMethod();
},
run : function() {
alert('done');
}
};
$(function() {
testObject.methodOne(run);
});
Any idea how can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 jQuery >= 1.5,那么您应该使用
Deferred
功能:本示例中的 jsFiddle:http: //jsfiddle.net/3Z4zu/
更清晰/重构的版本可能如下所示:
http://jsfiddle.net/3Z4zu/1/
Provided you are using jQuery >= 1.5, then you should use the
Deferred
-functionality:jsFiddle for this example: http://jsfiddle.net/3Z4zu/
A cleaner/refactored version could look like this:
http://jsfiddle.net/3Z4zu/1/
您可以定义一个在动画停止时触发的自定义事件,例如:
在每个函数中,您应该触发该事件:
编辑:我知道我丢失了原始代码的一些功能(定义要调用哪个函数作为回调) )但我想你基本上会知道我的想法。
You can define a custom event to be fired when an animation stops, for example:
In each of your functions you should trigger that event:
EDIT: I understand that I lost some functionality of your original code (defining which function to be called as callback) but I think you'll know basically what I had in mind.
您可以对动画函数调用进行计数,并在每个动画回调中减少该数字。在回调中,如果所有其他动画都已完成,则调用“主”回调:
You can count the animate function calls and decrement that number in each animation callback. In the callbacks, if all the other animations have finished you call the "master" callback :
您可以让每个动画函数的所有成功回调增加一个计数器并调用相同的函数(您的
callbackMethod
)。在
callbackMethod
中,您检查计数器是否已达到 3,然后仅在达到时执行所需的代码。或者以相反的方式从 3 到 0,或 3 个独立的布尔值,此时您有很多选择。
You could have all of the success callbacks from each animate function increase a counter and call the same function (your
callbackMethod
).In
callbackMethod
, you check to see if the counter has hit 3 and then only perform your desired code if it has.Or work the opposite way from 3 down to 0, or 3 separate booleans, you've got many options to you at that point.