1

i use jquery for a long time and thinking of creating a plugin myself. but no matter how easy the tutorial was, i cant really grasp the idea of chaining. suppose i have this very simple plugin....

(function($){
      $.test = function(){

        $.test.one = function(){ alert("1");};

        $.test.two = function(){ alert("2");};

        return this.each(function(){
             (what to write here????)
        });
      };
 })(jQuery);

what i want to accomplish is, when i call like eg

var myplugin = $.test();
myplugin.one().two();

but it returns me errors. sorry, i tried many times googling simple tutorials but i cant get this working

1
  • If you haven't yet, I strongly recommend you to take a look at the jQuery's plugins/authoring guide docs.jquery.com/Plugins/Authoring Commented Sep 5, 2012 at 8:36

3 Answers 3

7

Are you trying to do this?

(function($){
    $.fn.test = function(){
        var self = this;
        this.one = function(){ alert("1"); return self; };
        this.two = function(){ alert("2"); return self; };
        return this;
    };
}(jQuery));


var myplugin = $().test();
myplugin.one().two();

Example Fiddle: http://jsfiddle.net/kzzMY/

As a side note I strongly suggest this useful resource on the subject : http://jqueryboilerplate.com/

Sign up to request clarification or add additional context in comments.

3 Comments

wow! this works! but can i ask you what is the difference of $.fn.test from $.test?
$.fn.test is the properly and correct way to add a function to jQuery prototype and thus, create a plugin (while $.test is like just adding a property to jQuery function)
oh i see, thanks so much man! i will try and look at the link!
1

here is my plugin template:

(function($){
  $.fn.pluginName = function(){

  }
  return this;
})(jQuery)

Comments

1

Never written a jQuery plugin myself but surely you need to return something from your methods one and two (probably 'this') or there is no object for the second method in your chain to be called on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.