Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 = function(fn)
    {
        alert("function set.");
    }
  };

})(jQuery);

i'm using this code to initialize it (on a div):

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

now the problem: when trying to apply the setFN function:

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

i'm getting an error: button.setFN is not a function

i already tried this.bind instead but didn't help. anyone knows what's wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

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) {
          return this.each( function() {
             new $.TButton(this,callback);
          });
      }
  });

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...