Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created August 2, 2010 20:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elijahmanor/505225 to your computer and use it in GitHub Desktop.
Save elijahmanor/505225 to your computer and use it in GitHub Desktop.
//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