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!
As you said ‘that seems dirty for me’, that’s exactly what the jQuery page that you mentionned says :
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 chainyourPluginwith other methods that are in theMethodsclass.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.