2013-03-21 63 views
0

我開始瞭解更多關於jQuery插件模式的知識,但我遇到了一些問題。見下面的代碼。我想用onclick函數訪問我的插件選項/默認值,但我不知道如何。如何從事件函數中訪問其他方法?

function SomePlugin(element,options) 
{ 
    this.$el = $(element); 

    this.options = $.extend({}, 
    { 
     button: '#button', 
     someVariable:'fuu', 
     anotherVariable:'bar' 

    },options); 

    this.init(); 
} 

SomePlugin.prototype = 
{ 
    init:function() 
    { 
     var button = this.$el.find(this.options.button) 

     button.on('click', this.onClick); 
    }, 
    onClick: function(event){ 
     // Need to access the options (someVariable, anotherVariable) here... how? 
    } 
}; 


$.fn.somePlugin = function(options) 
{ 
    return this.each(function() 
    { 
     if(!$.data(this,'somePlugin')) 
     { 
      $.data(this,'somePlugin',new SomePlugin(this,options)); 
     } 
    }); 
}; 

我試過了下面的代碼,但是由於某種原因,這種感覺並不正確。有沒有更好的辦法?此外,我還有其他關於我的插件結構的建議或提示,請讓我知道。 BTW我已經離開了jQuery的包裝的可讀性

function SomePlugin(element,options) 
{ 
    this.el = element; 
    this.$el = $(element); 

    this.options = $.extend({}, 
    { 
     button: '#button', 
     someVariable:'fuu', 
     anotherVariable:'bar' 

    },options); 

    this.init(); 
} 

SomePlugin.prototype = 
{ 
    init:function() 
    { 
     var button = this.$el.find(this.options.button) 

     button.on('click', {instance:this}, this.onClick); 
    }, 
    onClick: function(event){ 
     // Options can be accessed using event.data.instance.options ... is there an easier way? 
    } 
}; 


$.fn.somePlugin = function(options) 
{ 
    return this.each(function() 
    { 
     if(!$.data(this,'somePlugin')) 
     { 
      $.data(this,'somePlugin',new SomePlugin(this,options)); 
     } 
    }); 
}; 

回答

0

我已經回答了我的問題。訣竅是使用jQuery的$ .proxy()方法是這樣的:

button.on('click', $.proxy(this.onClick), this); 

並提及點擊的按鈕(因爲「這」現指SomePlugin類):

onClick: function(event){ 
    // This now refers to SomePlugin class, yay! 
    // Use event.target instead of this to refer to the clicked element 
    $(event.target).text(this.options.someVariable); 
}