13
jQuery Object Oriented Event Handling
Filed Under (Website Monitoring) by admin on 13-04-2010
Using jQuery, its easy to write event handlers for all kind of events
that can occur in the DOM. It gets a little harder when the callback function is part of a object, and you want the function to have access to the object using this.
In jQuery you write a event handler as the following:
function clicked(event) {
alert(this)
}
$("#element").bind('click', clicked)
The this variable is going to contain the element that triggered the event. This
is very useful if you are using function to handle your events and not methods on
an object. But say you want to do something like this.
person = {
full_name : "Vitaly Babiy",
clicked : function(event) {
alert(this.full_name)
}
}
$("#element").bind("click", person.clicked)
This will not work as excepted since the this variable is still going to have a
reference to the element object that triggered the event and not the person object
that the method is in.
jQuery 1.4 comes with a solution for this problem. First i will show you the code
and explain what it does later.
person = {
full_name : "Vitaly Babiy",
clicked : function(event) {
alert(this.full_name)
}
}
$("#element").bind("click", $.proxy(person.clicked, person))
We still have the same person object the only difference is the callback used in the bind function. We are using the $.proxy(or jQuery.proxy) function,
which allows us to give it a function as the first argument and a context
to be set as the this variable when the callback is called as the second argument. In the above example we are telling it to set the person object as the context for the call, mean this will be a reference to the person object.
Lastly here is a link to the docs.
Question or comments, you know where they go.
monitoring.eu/wp-content/plugins/wp-o-matic/cache/9b396_aAgC3T9oYkw” height=”1″ width=”1″ />
google.com/~r/HowsthecomBlog/~3/aAgC3T9oYkw/” rel=”nofollow”>Go to Source


