使用插件内部的功能

时间:2009-12-06 13:25:34

标签: javascript jquery function jquery-plugins

我写了一个小jQuery按钮插件 - 它包含一个应用onclick-function的方法 - 这里是代码

(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

我已经尝试了这个。但是没有帮助。 谁知道什么是错的?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

该功能是tButton。如果应该这样读:

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

答案 2 :(得分: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);
      }
   });          
}

现在你可以使用它来初始化:

$("button").tButton();

可以通过以下两种方式致电setFN

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