jQuery Name Spacing and setTimeout

jQuery Name Spacing and setTimeout

本文关键字:setTimeout and Spacing Name jQuery      更新时间:2024-02-07

我正试图按照此处的方向使用名称间距构建一个jQuery插件:http://docs.jquery.com/Plugins/Authoring#Namespacing

现在我遇到了一个问题,我的插件需要使用setTimeout来激发它的一个方法

var jScrollerMethods = {
    ready:function(){
        return this.each(function(){
        var self = this,
    $this = $(this),
        data = $this.data('jScroller');
        settings.timeoutHandle = setTimeout(function(){
            if(settings.direction = "left"){
                this.moveLeft();
            }else if(settings.direction = "right"){
                this.moveRight();
            }
        }, settings.time);
        $this.data('jScroller', {
            settings: settings,
            element: this
        });
    });
}
$.fn.jScroller = function(call){
    if ( jScrollerMethods[call] ) {
      return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof call === 'object' || ! call ) {
        if (call) { $.extend(settings, call); }
        return jScrollerMethods.init.apply( this, call );
    } else {
        $.error( 'Method ' +  call + ' does not exist on jQuery.jScroller' );
    } 
}

但正如我所想的那样,setTimeout是从Window而不是插件对象触发的,因为我希望插件在每页上可以使用一次以上,所以我不能只将当前对象保存到窗口中,我该如何实现这一点?

我发现当在return this.each之外使用this时,会给你准确的选择器结果

所以通过一些工作我已经做到了,

var jScrollerMethods = {
    ready:function(){
        selector = this;
        return this.each(function(){
        var self = this,
    $this = $(this),
        data = $this.data('jScroller');
        settings.timeoutHandle = setTimeout(function(){
            if(settings.direction = "left"){
                selector.jScroller("moveLeft");
            }else if(settings.direction = "right"){
                selector.jScroller("moveRight");
            }
        }, settings.time);
        $this.data('jScroller', {
            settings: settings,
            element: this
        });
    });
}
$.fn.jScroller = function(call){
    if ( jScrollerMethods[call] ) {
      return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof call === 'object' || ! call ) {
        if (call) { $.extend(settings, call); }
        return jScrollerMethods.init.apply( this, call );
    } else {
        $.error( 'Method ' +  call + ' does not exist on jQuery.jScroller' );
    } 
}