Skip to content Skip to sidebar Skip to footer

Using Functions From Inside A Plugin

i wrote a little jQuery button plugin - it contains a method for applying the onclick-function - here's the code (function ($) { $.fn.tButton = function () { this.setFN =

Solution 1:

You aren't returning anything from the tButton function so the value of tButton isn't what you think it is. Try returning this from tButton() so to get the jQuery object back out of it. Also, I don't think this is a good way to do it as you are basically extending jQuery in a non-standard way. A better way would be to have tButton take the callback function as an argument and apply it to just the matching elements. I would also use a different pattern for defining the plugin (similar to the UI plugins).

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

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

Solution 2:

The function is tButton. If should read like this:

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

Solution 3:

Here is the pattern you can use do this:

$.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){
   returnthis.each(function(){ // Don't break the chainif(! func){ // If no parameter is passed, this is a constructor
        (new $.TButton(this));
      } else { // If the parameter (expected to be a function), call setFNvar button = $(this).data('TButton');
         if(button) button.setFN(func);
      }
   });          
}

Now you can initialize using this:

$("button").tButton();

And can call setFN two ways like this:

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

Post a Comment for "Using Functions From Inside A Plugin"