Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript plugins design pattern like jQuery

Could someone write down a very simple basic example in javascript to conceptualize (and hopefully make me understand) how the jQuery plugin design pattern is done and how it works?

I'm not interested in how creating plugin for jQuery (so no jQuery code here at all). I'm interested in a simple explanation (maybe with a bit of Javascript code) to explain how it is done the plugin concept.

Plz do not reply me to go and read jQuery code, I tried, but I it's too complex, otherwise I would have not post a question here.

Thanks!

like image 726
Marco Demaio Avatar asked May 20 '10 11:05

Marco Demaio


2 Answers

jQuery has a library of functions stored in an internal object named fn. These are the ones that you can call on every jQuery object.

When you do $("div.someClass") you get a jQuery object containing all <div> elements of that class. Now you can do $("div.someClass").each( someFunction ) to apply someFunction to each of them. This means, that each() is one of the functions stored in fn (a built-in one in this case).

If you extend (add to) the internal fn object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log(). You could append this function to $.fn, and then use it as $("div.someClass").log().

Every function appended to the fn object will be called in such a way that inside the function body, the this keyword will point to the jQuery object you've used.

Common practice is to return this at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction ).

There are several ways to append functions to the $.fn object, some safer than others. A pretty safe one is to do:

jQuery.fn.extend({
  foo: function() {
    this.each( function() { console.log(this.tagName); } );
    return this;
  }
})
like image 180
Tomalak Avatar answered Nov 02 '22 17:11

Tomalak


Tomalak already posted almost everything You need to know.

There is one last thing that helps jQuery do the trick with the this keyword.

it's amethod called apply()

var somefunction=function(){
alert(this.text);
}
var anObject={text:"hello"};

somefunction.apply(anObject);
//alert "hello" will happen

It really helps in creating abstractions so that framework/plugin users would just use this as intuition tells them, whatever there is inside Your code

like image 32
naugtur Avatar answered Nov 02 '22 16:11

naugtur