jquery 使用承诺调用两次动画完成
jquery animate complete using promise calling twice
在我的jquery插件中,完成动画后,我被称为"destroy"函数两次..有人纠正我的错误我做什么?
功能:
;(function ( $, window, document, undefined ) {
$.fn.BackendProcess = function(){
var that = this;
destroy = function(){
console.log(arguments.callee.caller.toString());//consoling 2 times
}
that.bind( "myEventStart", function( e ) {
$(this).css({width:"500"});
});
that.bind( "myEventEnd", function( e ) {
setTimeout(function(){
$(that).animate({width :"100"},{
easing: 'swing',
duration:2000
}).promise().done(function(){destroy()});
})
});
return{
start:function(){
that.trigger("myEventStart");
},
stop:function(){
that.trigger("myEventEnd");
},
destroy:function(){
console.log("distroy starts");
}
}
}
})( jQuery, window , document );
$(".myButton").BackendProcess().start();
$(".myButton").BackendProcess().stop();
这是演示
正如@Frederic指出的那样,您在事件中遇到了设计问题。可以使用on/off
而不是bind
来修复它,如下面的代码所示。它通过在初始化时关闭所有重复事件来删除它们。
工作演示
;(function ( $, window, document, undefined ) {
$.fn.BackendProcess = function(){
var that = this;
that.off();
destroy = function(){
console.log(arguments.callee.caller.toString());
}
that.on( "myEventStart", function( e ) {
$(this).css({width:"500"});
});
that.on( "myEventEnd", function( e ) {
setTimeout(function(){
$(that).animate({width :"100"},{
easing: 'swing',
duration:2000
}).promise().done(function(){destroy()});
})
});
return{
start:function(){
that.trigger("myEventStart");
},
stop:function(){
that.trigger("myEventEnd");
},
destroy:function(){
console.log("distroy starts");
}
}
}
})( jQuery, window , document );
$(".myButton").BackendProcess().start();
$(".myButton").BackendProcess().stop();
每次
调用$.fn.BackendProcess()
时,您都将处理程序绑定到myEventStart
和myEventEnd
。
由于您调用了两次,因此同一个处理程序绑定了两次myEventEnd
,因此并行执行两个动画,从而产生两个不同的 promise 和两次调用 console.log()
。
您必须修改设计,以便处理程序仅绑定一次,即使多次调用$.fn.BackendProcess()
也是如此。
相关文章:
- Meteor Router数据函数被调用两次
- 从MySQL数据库中获取输入数据需要两次页面刷新
- Module.start()已激发两次
- Jquery点击事件必须点击两次
- Append元素在运行两次函数后不显示
- 防止双击执行两次jQuery post请求
- 我必须点击两次才能激活任何按钮操作(离子/角度)
- 单击jQuery会激发两次
- 如何避免在树上走两次
- 使用wow.js显示两次动画对象
- jquery 使用承诺调用两次动画完成
- .is(“:animated”) 选择器在动画期间返回 true,并调用两次
- jquery 动画在关闭时出现两次
- Css动画发射两次;闪烁”;在firefox中
- Javascript/jQuery:动画发生两次
- 画布上的动画同时循环两次
- jQuery动画:回调调用两次
- 动画Javascript显示/隐藏按钮两次
- jQuery动画只工作一次或两次
- jQuery动画在运行时触发回调两次