开发者

SetInterval Collides When Calling a jQuery Plugin More than Once

I'm working on a custom jQuery plugin that makes use of SetInterval, but it breaks when it's called more than once.

I have something sort of like this:

(function($){
    $.fn.myplugin = function(options) {

        var defaults = {};
        var options = $.extend(defaults, options);
    var interval;

        this.each(function() {
            //etc.
            interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        });

        function doMyOtherFunc(options) {
            //etc
        }

    }
})(jQuery);

Functionality works as expected if I call it once, but if I call it again on a second element it breaks.

$('#myelement').myplugin({'option1', 'option2'});
$('#myotherelement').myplugin({'option1', 'option2'});

Somehow, the interval in the second instance overrides the one on 开发者_Python百科the previous element, data and all. (But the styling passed doesn't get screwed up.) Is this a weird limitation of setInterval, or am I doing something wrong?


You have to make the interval handle private to each element. For this, you could use $.data:

    this.each(function() {
        var interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        $(this).data('myplugin-interval', interval);
    });

And you could retrieve the interval this way:

$(this).data('myplugin-interval');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜