How jQuery works: jQuery Object Methods
Before starting to write your own plugins, you must pretty understand how jQuery works first. Take a look at this code:
This is a basic jQuery code, but do you know what’s happening behind the scenes? When you use the $ function to select elements, it gives back a jQuery object which contains all of the methods you’ve been using (.css(), .click(), etc.) and every element that fits your selector. These methods come from the $.fn object.
To help your plugin survive in the real world, there are a couple of things you need to do for it. When you link 4 or 5 actions onto one selector, you’re coming to the chaining feature of jQuery. This feature is done by having all jQuery object methods return the original jQuery object again (exceptions: .width() only returns the width of the selected element, not chainable). Making your plugin method chainable just takes one line of code:
Protecting the $ Alias and Adding Scope
Adding Private Methods and Variables
Remember adding a private variable and enabling its use is only possible by using the Immediately Invoked Function:
These private methods can solely be called from within the scope of the function and only other private methods or public methods have the authority to call them. This is also for accessing the private variables.
Adding Public Methods
Public methods can be accomplished by nearly the same process as what you just did with private methods. There’s just one difference between these 2, the execution of the method. The method becomes public when it is supplied with a ‘this’ operator. The purpose of adding such public methods could be either to perform a function or to access the public variables and methods from outside the scope of the function.
Accepting Options for Plugin Customization
In some cases, your plugins turn more complex as you continue to add to them. Hence, it is a smart idea to make your plugin be capable of accepting some options and make them customizable. The easiest way to do this, especially when there are a lot of options, is with an object literal.
Putting it All Together
Combining all techniques we’ve discussed, the result is the following small plugin as below:
As you can see, the syntax ‘each()’ is used to loop through a collection of elements. Also, the return value for this method is the ‘this.append()’ which accepts the callback. We will be able to see what element is being appended to in the collection whereupon it returns.