Forum Moderators: open

Message Too Old, No Replies

jquery implementation of a command

         

Mister_L

4:43 pm on Apr 10, 2011 (gmt 0)

10+ Year Member



Hi,

I would like to understand how jquery developers implemented the following command, structure-wise only:

jquery(document).ready(.........);

So if I'm correct, we have a function called "jquery" that accepts "document" as a parametes, and another function "ready" which is nested inside jquery function?

Thanks for your help.

mbabuskov

10:00 pm on Apr 10, 2011 (gmt 0)

10+ Year Member



The line between functions and object is very thin in JS, so your definition could be called correct. Anyway, I like this version better:

"jquery" is a function that accepts "document" as a parameter and returns an object that has a "ready" member function.

If you did some object-oriented programming, you would be familiar with member functions.

Mister_L

11:15 am on Apr 11, 2011 (gmt 0)

10+ Year Member



I tried to implement something similar to jquery's click function as follows (I know it's not how they really implement it, it is just for the sake of learning):


function jquery(obj) {
return document.getElementById(obj);
}

function click(myfunction) {
this.onclick=myfunction;
}

Then I tried to add the event to a button with id "btn" by:


jquery("btn").click(function(){
alert ('click event added');
});

Why doesn't it work?

Thanks.

Fotiman

12:56 pm on Apr 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



jQuery is an object that has many methods. Most of those methods will return a jQuery object as well. This allows method calls to be "chained".

jQuery(document)

The return value of this call is a jQuery object which has a "ready" method. In your example, though, you are returning the DOM element with the ID that was passed in. Then you're trying to call the "click" method of that element, but there is no such method defined for DOM elements.

Mister_L

11:53 am on Apr 12, 2011 (gmt 0)

10+ Year Member



OK, so how would you modify my functions so that:

jquery("btn").click(function(){
alert ('click event added');
});

would work as expected? If you write down the code it will help me a lot since I'm rather new to js objects.

daveVk

1:18 pm on Apr 12, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



function jquery(id) {
var newObj = {};
newObj.el = document.getElementById(id);
newObj.click = function(myfunction) {
this.el.onclick = myfunction;
};
return newObj;
}