0

私は多くの js スクリプトと jQuery プラグインを書いてきたので、ここに私のジレンマの要約された疑似コード シナリオを示します。

プラグインに渡すメソッド オブジェクトを定義する適切に作成された jQuery プラグインがあるとします。

// OUR HYPOTHETICAL jQUERY PLUGIN
(function($){

var methods = {
    init : function(options){
        var setup = $.extend({
            'speed' : 300,
            'msg' : 'blah'
        }, options)

        return this.each(function(){
            var animation = setInterval(function(){ ... },1000)
            ...
        })

    },
    stop : function(){
        window.clearInterval(animation); // DOES NOT WORK
    }
};

$.fn.somePlugin = function(method){
     // Method calling logic
        if ( methods[method] ) {
          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
            $.error( 'Bad Method...' );
        }   
};

})(jQuery)

このプラグインを div にインスタンス化することを想像してみましょう$('#someDiv').somePlugin();

この時点までのすべてが正常に機能し、電話をかけることができます... $('#someDiv').somePlugin('stop');

ただし、stopメソッドの内部では、プラグインの初期化中に作成されたアニメーション プロパティのインスタンスにアクセスする方法を理解できません。

#someDivにバインドされたプラグインに関連付けられているアニメーション変数の特定のインスタンスを取得する方法に関するアイデア。

4

2 に答える 2

1

アニメーション変数がローカルであるため、これは機能しません。アニメーション (1 つの配列) 変数をプラグイン プロパティとして使用して、プラグイン インスタンスに対してローカルになるようにします。このアプローチを使用すると、必要なものが得られると思います。

一例:

HTML:

<button id="btnStart"/>Start</button>
<button id="btnStop"/>Stop</button>

JavaScript:

var obj = {
    size: 5,
    animationsId: [],
    start: function() {
        for ( var i = 0; i < this.size; i++ ) {
            this.animationsId[i] = setInterval( function() {
                console.log( "aaa" );
            }, 500 );
        }
    },
    stop: function() {
        for ( var i = 0; i < this.size; i++ ) {
            clearInterval( this.animationsId[i] );
        }
    }
};

$( "#btnStart" ).click(function(){
    obj.start();
});

$( "#btnStop" ).click(function(){
    obj.stop();
});

jsFiddle: http://jsfiddle.net/davidbuzatto/3fDHF/

于 2012-07-23T21:48:51.547 に答える
0

各要素のデータ内に間隔トークンを格納できます。例えば...

var animation = setInterval(function(){ ... },1000)
$(this).data('somePlugin', {animationInterval: animation});

その後、特定の要素にアクセスできます...

window.clearInterval($(this).data('somePlugin').animationInterval);
于 2012-07-23T21:53:48.890 に答える