在我的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()
也是如此。