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

This is not working because the animation var is local. Use the animation (one array) var as a plugin property, so it will be local to the plugin instance. I think that using this approach you will achieve what you need.

One example:

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 回答