Javascript jquery使用承诺调用两次来设置完成动画
在我的jquery插件中,在完成一个动画后,我被调用了两次“销毁”函数。。有人纠正我的错误吗 功能:Javascript jquery使用承诺调用两次来设置完成动画,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,在我的jquery插件中,在完成一个动画后,我被调用了两次“销毁”函数。。有人纠正我的错误吗 功能: ;(function ( $, window, document, undefined ) { $.fn.BackendProcess = function(){ var that = this; destroy = function(){ console.log(arguments.callee.caller.toStrin
;(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();
每次调用
$.fn.BackendProcess()
时,您都将处理程序绑定到myEventStart
和myEventEnd
由于要调用它两次,同一个处理程序将两次绑定到myEvent
,因此并行执行两个动画,从而产生两个不同的承诺,并两次调用console.log()
即使多次调用
$.fn.BackendProcess()
,您也必须修改您的设计,以便只绑定一次处理程序。正如@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();