Write the jquery plugin and the $ .something construct

I am currently working on a jquery plugin and am looking at other plugin code. I found a general way to write it passing through an object, something like:

$.fn.myplugin = function(method){ //... some code object = new $.myobject(param); //... other code // myobject definition $.myobject = function(param){ //.... my object code } } 

I cannot understand how the definition of $ .myobject works and why many developers use it to define their plugins.

Could you give some information and a tutorial / documentation link if possible?

+4
source share
3 answers

The ability to add properties at runtime to javascript objects is what makes each javascript object an 'expando' object.

There is an explanation here.

Stack overflow question for javascript expando objects

Hope this helps :)

+1
source

The true power of jQuery is its ability to quickly and easily select and use the DOM. Fortunately, we can expand this power by adding our wrapper methods that control the selected DOM elements, as we consider appropriate. By adding wrap-per methods, we automatically get the use of powerful jQuery selectors to select and choose which elements should work, without having to do all the work ourselves.
Given what we know about JavaScript, we could probably figure out how to add function functions to the $ namespace, but this is not necessarily true for the wrapper. Theres is concise jQuery-specific information that we need to know: to add shell methods to jQuery we must assign them as properties for an object named fn in the namespace. The general template for creating a wrapper function is

 $.fn.wrapperFunctionName = function(params){function-body}; 

Lets you come up with a trivial wrapper method to set the color of matching DOM elements to blue:

 (function($){ $.fn.makeItBlue = function() { return this.css('color','blue'); }; })(jQuery); 

http://www.manning.com/bibeault2/

+1
source

I think this is just one of many ways to avoid global pollution. Developers set their plugin as a property of jQuery itself to make it unacceptable with window.myPlugin

Or do they prefer the design

$.tooltip(someObjects, "text")

than

$(someObjects).tooltip("text")

or want to accept both.

However, as a method, to avoid code pollution, I would recommend self-starting functions rather than a jQuery extension with meaningless wrappers.

 (function($) { // put here any variables or functions you need // they will stay within the self invoking function scope function setup(element) { // add extra features to the matched element } $.fn.tooltip = function() { return this.each(function(index, element) { setup(element); }); } })(jQuery); 

If this answers your question, you can read more in one of my articles.

0
source

All Articles