Pergunta

I'm trying to make a simple jQuery Plugin. I would like to call it's methods chained like this:

$("#div").myPlugin({
    /* options */
}).add(".span", {
    /* options */
}).add(".span", {
    /* options */
}).run();

I found some basic tutorials for calls like this:

$("#div").myPlugin("add", "foo");

or

container = $("#div").myPlugin();
container.myPlugin.add("foo");
container.myPlugin.run();

but it's not what I want. The basic tutorials are almost the same everywhere and I don't know what I have to google for.

The jQuery tutorial shows how to maintain chainability.

The only way I know is to write a plugin for every method but that seems dirty for me.

jQuery.fn.myPlugin = function(); // returns this
jQuery.fn.myPluginAdd = function(); // returns this
jQUery.fn.myPluginRun = function();
$("#div").myPlugin().myPluginAdd("item1").myPluginRun();

Thanks in advance!

Foi útil?

Solução

As you said 'that seems dirty for me', that's exactly what the jQuery page that you mentionned says :

Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object.

(function( $ ){

  $.fn.tooltip = function( options ) { 
    // THIS
  };
  $.fn.tooltipShow = function( ) {
    // IS
  };
  $.fn.tooltipHide = function( ) { 
    // BAD
  };
  $.fn.tooltipUpdate = function( content ) { 
    // !!!  
  };

})( jQuery );

Chainability is all about what your return. If you want to chain the methods from your plugin you will have to return an object that contains your methods. Fiddle : http://jsfiddle.net/ma4nj/

As you can see, when you first call yourPlugin(), an object containing your plugin methods is returned. That way you can chain yourPlugin with other methods that are in the Methods class.

If you look at the add() function you can see that I returned the instance again, so nothing new here, as I've just explained, I did that so the methods are chainable.

Give it a go, try adding your own methods. Keep in mind that you won't be able to chain your plugin methods with the jQuery ones with that technique. Actually you can if you add a method within the plugin to disable the plugin chain like this : http://jsfiddle.net/ma4nj/1/

There's probably a better way to do what I've done but I hope that helps anyway.

Outras dicas

Bombastic, for plugin there is best tutorial available on net is below:

https://tutsplus.com/author/jeffreyway/?q=true&filter_topic=35

i hv seen his jquery plugin video. Really nice to see and learn from it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top