1

我正在尝试使用名称间距系统创建一个 jQuery 插件,所以这是我所拥有的一个小例子

(function($){
var jScrollerMethods = {
    init:function(config){
        this.settings = $.extend({
            'option':'value'
        }, config);
    },
    getOption:function(){
        return this.settings.option;
    }
}

$.fn.jScroller = function(call){
    if ( jScrollerMethods[call] ) {
      return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof call === 'object' || ! call ) {
      return jScrollerMethods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  call + ' does not exist on jQuery.jScroller' );
    } 
}

$(".selector").jScroller({'option':'newValue'});
var opt = $(".selector").jScroller("getOption");

})(jQuery);

opt变量不起作用,并且它不应该像在声明这样的函数时this那样init:function(){.. this工作保存到窗口,因为在不同的选择器上运行的 jScroller 实例可能不止一个,我似乎只是找到或弄清楚了initgetOption

4

1 回答 1

1

您需要为每个实例创建一个唯一的选项对象,并且需要将其与实例一起存储。jQuerydata()非常适合这个。Object.create()这使用您可能有意见的 Crockford's 。

if (typeof Object.create !== 'function') {
  /* 
     Function: create

     create a new instance of an object using an existing object as its prototype

     Parameters:
        o - the object serving as the new prototype

     Returns:
        a new object
  */         
  Object.create = function (o) {
     function F() {}
     F.prototype = o;
     return new F();
  };

}

然后在您的 init 函数中,添加如下内容:

return this.each(function() {            
    var self = this,
    $this = $(this),
    data = $this.data('jScroll'),
    opts = Object.create(options);

    if (!data) {
        $this.data('jScroll', {
          options: opts, // this is the options object that you'll access later
          element: this // you may not need this
        });
    }
}); 

你的getOptions方法执行这个:

var data = this.data('jScroll');
if (data.options[options]) { return data.options[options] };

我在调用 init 之前进行了设置合并:

} else if ( typeof call === 'object' || ! call ) {
    if (call) { $.extend(settings, call) } // this expects a settings variable defined with defaults
    return jScrollerMethods.init.apply( this, call );
}
于 2012-07-18T18:27:31.573 回答