Wednesday, March 23, 2016

jQuery Plugin and special javascript literal

When you read javascript codes written by other developers, chances are those code may contain jQuery plugin codes. Usually those codes containing following format:
Type 1:
(function($) {
    $.fn.jPluginName = {
    },

    $.fn.jPluginName.defaults = {
    }
})(jQuery);
Type 2:
(function($) {
    $.jPluginName = {
    }
})(jQuery);
Type 3:
(function($){
    //Attach this new method to jQuery
    $.fn.extend({ 
        var defaults = {  
        }  
        var options =  $.extend(defaults, options);  
        //This is where you write your plugin's name
        pluginname: function() {
            //Iterate over the current set of matched elements
            return this.each(function() {
                //code to be inserted here
            });
        }
    }); 
})(jQuery);
A js code block looks like (function(){})()  actually defined a function and execute it. The parameter $ means the parameter is a reference. 

In jQuery, the fn property is just an alias to the prototype property.
So jQuery.fn === jQuery.prototype

Following is a simple javascript constructor function using prototype to extend the original class:
function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property
Following is a normal structure similar to the architecture of jQuery:
(function() {
  var foo = function(arg) { // core constructor
      // ensure to use the `new` operator
      if (!(this instanceof foo))
          return new foo(arg);
      // store an argument for this example
      this.myArg = arg;
      //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
      init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:
foo.fn.myPlugin = function () {
    alert(this.myArg);
    return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"
Type 1: This is actually not a plugin, it's an object passed as a function, and new functions added to the object using prototype.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extension of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

Reference:

No comments:

Post a Comment