Chinchan Zu
Chinchan Zu

Reputation: 918

jquery: how can I chain functions?

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

Upvotes: 1

Views: 2187

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

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/

Upvotes: 7

Tim Croydon
Tim Croydon

Reputation: 1896

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.

Upvotes: 1

Mild Fuzz
Mild Fuzz

Reputation: 30691

here is my plugin template:

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

  }
  return this;
})(jQuery)

Upvotes: 1

Related Questions