2009-12-06 36 views
-2

我寫了一個小的jQuery按鈕插件 - 它包含應用的onclick功能的方法 - 這裏的代碼從插件內部使用功能

(function ($) { 
    $.fn.tButton = function() 
    { 
    this.setFN = function(fn) 
    { 
     alert("function set."); 
    } 
    }; 

})(jQuery); 

我使用此代碼初始化(上DIV):

var button = $("#myButton").tButton();

現在

問題:試圖應用setFN功能時:

button.setFN(function(){dosomething();}); 

我得到一個錯誤:button.setFN is not a function

我已經試過this.bind,而不是幫助。 任何人都知道什麼是錯的?

回答

0

函數是tButton。如果要這樣寫的:

var button = $("#myButton").tButton(function(){dosomething();}); 
+0

setFN涉及哪裏? ..:/ – Fuxi 2009-12-06 13:38:09

2

不必返回從TButton的功能過這麼TButton的價值是不是你認爲它是。嘗試從tButton()返回this以便將jQuery對象從其中取出。另外,我認爲這不是一個好的方法,因爲你基本上是以非標準的方式擴展jQuery。更好的方法是讓tButton將回調函數作爲參數並將其應用於匹配元素。我也會使用不同的模式來定義插件(類似於UI插件)。

(function ($) { 
    $.fn.extend({ 
     tButton: function(callback) { 
      return this.each(function() { 
      new $.TButton(this,callback); 
      }); 
     } 
    }); 

    $.TButton = function(elem,callback) { 
     $(elem).click(callback); 
    }; 
})(jQuery); 
+0

我試着添加返回這個tButton函數的結尾 - 同樣的錯誤。 我認爲你是正確的jQuery的標準,但我需要能夠分配/更改後按鈕功能。 – Fuxi 2009-12-06 13:46:46

+0

然後讓函數接受多個參數,並根據這些參數做不同的事情。例如,如果參數列表是字符串'click'和函數,請將click函數重新應用到元素,否則執行正常的操作。 – tvanfosson 2009-12-06 13:58:19

+0

感謝你的例子 - 看起來簡單而簡單:) 只有一個問題 - 它不會在螢火蟲調試..不知道,如果它是我的系統。 – Fuxi 2009-12-06 16:33:07

0

這裏是你可以使用這樣做的模式:

$.TButton = function(el){ 
    var $el = $(el); 
    $el.data('TButton', this); // Store a reference to the TButton object on the DOM element 
    // Use this.functionName to make it "public" 
    this.setFN = function(callback){ 
     // Namespace the click events so you don't accidently remove 
     // other click events bound to the button. 
     $el.unbind('click.tbutton').bind('click.tbutton', callback); 
    } 
} 

$.fn.tButton = function(func){ 
    return this.each(function(){ // Don't break the chain 
     if(! func){ // If no parameter is passed, this is a constructor 
     (new $.TButton(this)); 
     } else { // If the parameter (expected to be a function), call setFN 
     var button = $(this).data('TButton'); 
     if(button) button.setFN(func); 
     } 
    });   
} 

現在可以初始化使用此:

​​

而且可以調用setFN兩種方式是這樣的:

$("button").tButton(function(){ ... }); 
// or 
$("button").data('TButton').setFN(function(){ ... });