views:

36

answers:

4

I decide to write a plugin, but there is a moment I don't know,and i can't find documentation about it so I decide to ask here.

For example when we wrote

$("#some_element").nameOfPlugin();

There are a lot of functions in nameOfPlugin, but how some_element connects with the plugin?

An example, or a link to some documentation will be very helpful.

Thanks.

+1  A: 

you need to read plugins authoring for that.

this blog post is also a great sample to read.

Reigel
+2  A: 

nameOfPlugin is the prototypal method which when inserted with the script element, extends jQuery so any jQuery objects can contain the method.

All the internal code of nameOfPlugin happens inside of that prototypal method and the scope which is defined.

Simple example of how you are extending jQuery, using Human instead of jQuery.

function Human(){};
Human.prototype.attack = function() { alert('attack') };
var john = new Human;
john.attack();

As far as $() connecting to it, $() returns an array of DOM elements ( one or many ). The plugin gets invoked in the context of each of these, since the object owns the method because it is an instance of the jQuery constructor which owns the plugin methods you've been adding.

$('body').hide() translates to calling the jQuery.prototype.hide method using document.body the DOM reference as the context.

I suggest reading up on prototypal inheritance to understand this. A good resource would be Eloquent JS, particularly chapter 8.

meder
Actually the idea behind jQuery is to hide all the ugly protoypal parts away. I agree that it's a great idea to understand the fundamental basics, but I'm unsure if it's a good answer here.
jAndy
He's asking how a prototypal method is connected to the selection of elements and that's what I explained.
meder
@meder Thanks man. now i know what i need to read for more information. That is why i am asking questions here.
Syom
+2  A: 

In the jQuery prototype, the this keyword represents the elements selected.

F.ex:

$('#some_element').myPlugin();

$.fn.myPlugin = function() {
  console.log(this); // this = #some_element (jQuery instance)

  // looping through elements and returning the instance 
  // to allow further chaining:
  return this.each(function() {
    console.log(this) // this = #some_element (HTML element)
  });
}
David
+1  A: 

i don't know how search documentation about it

made my day!

http://www.jquery.com

It took me whole 5 seconds to get to http://docs.jquery.com/Plugins/Authoring for instance.

jAndy
cool answer! +1 ;)
Reigel
Why is this getting downvoted? Some real old grumps around here, obviously.
J-P