Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - 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 = 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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...