2013-10-07 31 views
0

在我的jquery插件,完成動畫後,我被稱爲「摧毀」功能兩次..任何一個糾正我錯誤,我做什麼?jquery動畫完成使用承諾調用兩次

功能:

;(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(); 

Here is the demo

回答

1

正如@Frederic指出,你的設計問題與事件有關。您可以使用on/off代替bind來修復它,如下面的代碼所示。它通過在初始化時關閉所有重複事件來移除它們。

Working DEMO

;(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(); 
+0

但它不會解決我的問題,原因是,當我開始我應該顯示事件結束preloader時,我需要顯示另一個元素可見。 – 3gwebtrain

+0

工作正常。你能否提供一些線索來理解這裏究竟發生了什麼......? – 3gwebtrain

+0

當然,基本上我們正在移除初始化的所有事件,它可以幫助我們移除重複的事件。 –

1

要綁定處理程序myEventStartmyEventEnd每次$.fn.BackendProcess()被調用。

由於您將其調用了兩次,因此相同的處理程序會綁定兩次到myEventEnd,因此兩個動畫並行執行,從而產生兩個不同的承諾,並且兩次調用console.log()

您必須修改設計,以便處理程序僅綁定一次,即使$.fn.BackendProcess()被多次調用。

+0

聽起來不錯。你能給我一些樣品嗎?或演示請? – 3gwebtrain