2012-07-18 46 views
1

我試圖使用有名字間隔系統創建一個jQuery插件,所以這是我有什麼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點設置爲init功能讓我怎麼做,以便它不應該工作的getOption功能可以訪問設置,但這些不能保存爲上可能會有不同的選擇運行jScroller的多個實例,我只是得到似乎找到或弄清楚

+0

你有沒有在調用時運行此'.selector'的DOM元素? – Mathletics 2012-07-18 15:54:03

+0

我會的,這上面沒有我的實際代碼,但我現在面臨這個問題的實現,我希望不要有救對抗的元素,如果你想到用'.attr(「jScrollerSettings」的,JSON。字符串化(this.settings));'然後用'.attr(「jScrollerSettings」)'其他方法有沒有做一個更清潔的方式,因爲這是可怕的,一些設置,我不是爲用戶更改那裏只是一個保存點 – HotHeadMartin 2012-07-18 15:58:03

+0

也許你應該顯示你的實際代碼;此代碼充滿了錯誤。 – Mathletics 2012-07-18 15:58:57

回答

1

你需要創建一個獨特的選項窗口對象爲每個實例,並且您需要將其與實例一起存儲。 jQuery data()非常適合這個。這使用Crockford的Object.create(),您可能有意見。

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(); 
    }; 

}在您的初始化函數

然後,添加這樣的事情:

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); 
} 
+0

嗨,感謝您的完美工作 – HotHeadMartin 2012-07-24 11:24:39