As we seen in our previous article on Extending jQuery :: Part 1 – Miniature Plugins, it helps to be able to quickly build some project specific plugins to help keep your code clean. However, sometimes we don’t always want a method that acts on an element. But rather a global type function like the $.ajax
method. Here we will take a look at how to create a standalone jQuery method for common tasks that can help keep our code clean.
A good example of this is the url.js method for parsing a url with some syntactical sugar. So we will take a look at this plugin and break it down for us.
For creating a standalone method we will not be creating a $.fn.methodName
style function but rather we will be extending jQuery using it’s built in extend()
method.
$.extend({ url: function(arg, url) { return window.url(arg, url); }, method2: function () { return 'blah'; } });
All we do is pass an object of functions into the extend method. This is just a json data object, so we can create multiple functions here by comma separating them. These methods would now be available in the jQuery object and we could call them without requiring an element.
$.url('?test', 'http://jquery.in30minutes.com?test=yay');
The code inside the url function is not important and you can take a look at the GitHub page if you are interested. theimportant part is the extend()
method of jQuery. From there we are just creating regular functions that do something and can also accept other arguments as we can see in the $.url()
example.