Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a jQuery plugin that is called like `$.myplugin.func()`?

I've written a simple jQuery plugin, but I'd like to make it more advanced so I can do things like:

$.myplugin.close();
$.myplugin.open();
$.myplugin.next();
$.myplugin.prev();

How can I write a plugin that can be called like this?

-------------------------Updated-------------------------

Thanks @Craig MacGregor, appreciate it.

But to call the function it need to be like below

$(this).myplugin.load();
like image 845
user1740052 Avatar asked Oct 12 '12 04:10

user1740052


2 Answers

You can assign an object to "myplugin" like so:

$.myplugin = {
  close: function(){ 
      //code
  },
  open: function(){
      //code
  },
  next: function(){
      //code
  },

  prev: function(){
      //code
  }
};
like image 141
Craig MacGregor Avatar answered Oct 18 '22 17:10

Craig MacGregor


Just An Example:

(funciton($) {
  var methods = {
    init: function() {},
    close: function() {},
    open: function() {},
    prev: function() {},
    next: function() {},
  };

  $.fn.myplugin = function (method) {
    if (methods[method]) {
      return methods[method].apply(this, [].slice.call(arguments, 1));
    } else if (typeof method == 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error( 'Method ' +  method + ' does not exist on myplugin' );
    }      
  };

}(jQuery));

//usage
$(selector).myplugin();

// call methods
$(selector).myplugin('close');
$(selector).myplugin('open');
$(selector).myplugin('next');
$(selector).myplugin('prev');
like image 30
xdazz Avatar answered Oct 18 '22 18:10

xdazz