2013-03-05 63 views
1

我使用extended jQuery Plugin Boilerplate來編寫一個插件,該插件具有公共方法來啓動/停止在插件中運行的動畫;這個動畫不是CSS氨基BTW,它只是一個計數器,所以我可以用每個step上的函數激發另一種方法。jQuery - 使用插件的公共方法停止插件內的動畫

動畫從init()方法中開始:

Plugin.prototype = { 
    init: function() { 
     // Place initialization logic here 
     // You already have access to the DOM element and 
     // the options via the instance, e.g. this.element 
     // and this.options 
     // you can add more functions like the one below and 
     // call them like so: this.yourOtherFunction(this.element, this.options). 
     console.log('init'); 

     $({ i: 0 }).animate({ i: 1000 }, { 
      duration: 1000 
     , step:  function() { console.log(this.i); } 
     }); 
    }, 
    stop: function() { //yourOtherFunction: function() { 
     // some logic 
     console.log('stop'); 

     $(this.element).clearQueue(); 
     $(this.element).stop(); 
    } 
}; 

而且不啓動就好了,當被稱爲像$('.some-elements').wheels();

我想辦法暫停或通過調用公共函數停止這個動畫,例如:

var timeout = window.setTimeout(function() { 
    $('#total.cont-email-wheel').wheels('stop'); 
}, 500); 

這個例子將通過停止在半路動畫(我的理解超時等的不準確),但它不;這就是我來到這裏的原因!

注意:stop在中途標誌處被記錄到控制檯,因此方法被正確調用。

我敢肯定,通過查看jQuery docs,我需要被調用的對象clearQueue()stop()進行動畫,在這種情況下是一個匿名對象({ i }),而不是元素(一個或多個),但我不知道如何做到這一點。

任何幫助將不勝感激;我試圖儘可能簡潔地解釋,但如果不清楚,我會盡力在評論中澄清!

謝謝!

回答

0

這似乎我是正確的假設,我需要調用該對象的clearQueuestop方法進行動畫,所以我擴展this.element與物業i,所以我可以動態顯示,而不是匿名的對象。

這意味着我現在可以調用clearQueuestop方法暫停this.element對象上的動畫,該對象可以通過插件中的任何方法訪問。

Plugin.prototype = { 
    init: function() { 
     // Place initialization logic here 
     // You already have access to the DOM element and 
     // the options via the instance, e.g. this.element 
     // and this.options 
     // you can add more functions like the one below and 
     // call them like so: this.yourOtherFunction(this.element, this.options). 
     console.log('init'); 

     $.extend(this.element, { i: 0 }); 

     $(this.element).animate({ i: 1000 }, { 
      duration: 1000 
     , step:  function() { console.log(this.i); } 
     }); 
    }, 
    stop: function() { //yourOtherFunction: function() { 
     // some logic 
     console.log('stop'); 
     console.log($(this.element)); 

     $(this.element).clearQueue(); 
     $(this.element).stop(); 
    } 
}; 

通過這樣做,我現在不需要我自己的公共方法停止動畫作爲jQuery的本地stop()方法會工作得很好。另外,如果我想暫停/恢復動畫,我現在可以使用已有的大量暫停/恢復插件。無需重新寫輪子!