Adding a Static Function to Your Plugin - J Query

Problem
In addition to making your plugin available through the jQuery function, you want to expose a static function. How can you add a static function to your jQuery plugin?

Solution

Adding a static method to your plugin requires extending the jQuery object in much the same way you would add a method. The difference is simply that functions are called without using jQuery selectors:

Calling the static methods available in your plugin is very straightforward, requiring only that you explicitly pass a valid object to operate on:

Discussion

Adding a static function within the scope of your plugin only requires adding a way for code outside of your plugin to call it. This is accomplished by attaching the functions to the jQuery object.
In the previous example, we’ve added a namespace object to aid in organizing our code better. If all that your plugin required was a single static function, it would be completely appropriate to expose your static function without adding a name spacing object.
After adding our name space object, we simply define our functions like norma land attach them to the namespace object we created. Doing this exposes our function to the global namespace, while allowing the contents of the functions to access private functions and variables.
Taking advantage of the static function is as simple as calling it using the jQuery object we attached it to. This function is called without utilizing jQuery selectors, so in order to operate on a DOM element, that element must be explicitly passed to the function.
A static function attached to the jQuery object is another example of the flexibility of the jQuery library. Your entire plugin could be made up of adding static functions that simply extend the jQuery core in interesting new ways. A static function could be the entry point you provide to your plugin, or it could be a simple shortcut method you’ve found useful that’s packaged in your plugin in a way that makes it easier to share with other developers. What ever the need, static functions can be a useful and powerful tool when building your own jQuery plugin.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics