Created
August 2, 2010 20:09
-
-
Save elijahmanor/505225 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Changing Event Handler Context | |
//You can access the context by using the "this" pseudo parameter. The context of most jQuery Event Handler's | |
//is the DOM element that caused the event. There may be times when you want to change the context (the value | |
//of "this") inside of your event handler. In that case, you should use the $.proxy() method. The $.proxy() | |
//method allows you to manually define what you want the context to be inside your event handler. | |
//Utilizing the $.proxy() method to change context | |
var contact = { | |
name: "jQuery", | |
sayHello: function() { | |
alert("Hello " + this.name); | |
} | |
}; | |
//The result is "Hello undefined" because "this" inside of sayHello refers to the "div" element that was | |
//clicked and it does not understand the "name" property. | |
$("div").click(contact.sayHello); | |
//The result is "Hello jQuery" because the "this" inside of sayHello refers to the contact object, which | |
//does have "name" defined as "jQuery". | |
$("div").click($.proxy(contact.sayHello, contact)); | |
//The result of this is also "Hello jQuery". This is just using a different syntax to setup the $.proxy(). | |
//Instead of passing the function and context, you pass the context and the the name of the function off of | |
//the context object. | |
$("div").click($.proxy(contact, "sayHello")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment