Quick Tip: Learning jQuery 1.4′s $.proxy
One of my favorite new features in jQuery 1.4 is the new $.proxy method. It allows us the ability to force a particular context when calling a method. In JavaScript, there can be times when it’s difficult to hold on to the this keyword. For example, when it’s bound to some event handler, this now refers to the target of the handler, rather than your desired object.
If this sounds a bit confusing, don’t worry; today’s four-minute video quick tip should clear things up.
// Create an object.
var obj = {
// this = obj
somevar : 'some value',
doSomething : function() {
alert(this.somevar);
}
};
// When bound to an event handler, this will
// refer to the target of the handler, or the div - not obj.
$('div').click(obj.doSomething); // undefined.
// With $.proxy, we pass two parameters.
// 1. The method to call.
// 2. The context.
// In this case, we're forcing obj to once again be equal to this.
$('div').click( $.proxy(obj.doSomething, obj) ); // some value
Be sure to refer to the jQuery API for more information on $.proxy!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
- http://www.moscreative.com Serhiy
- snaKeSz
- Elijah
- http://www.nouveller.com/ Benjamin Reid
- http://edgespan.de Alexander Trefz
- Daniel
- http://www.BryanWatson.ca Bryan Watson
- http://www.appchain.com Ciprian
- JoeCianflone
- http://www.thecssninja.com/ Ryan
- salman
- http://www.newskycars.com/ newskycars
- Blink Interactive
- jasonnn
- Leigh Kaszick
- http://www.stylisticweb.com/blog/ Mehreen Baakza
- orihime
- http://www.evestudio.fr evestudio
- RCKY
- http://www.jordanwalker.net Jordan Walker
- http://wptricks.net WP Tricks
- http://www.michaelnaman.com Michael Naman
- http://www.freshclickmedia.com Shane
- http://bloggerzbible.blogspot.com/ Bloggerzbible
- http://www.gnomon-design.gr Vassilis Mastorostergios
- Leigh Kaszick
- http://johnweis.com/ John Weis
- http://arturoguzman.ca Arturo
- http://www.qualitystorefixtures.com John Store
- http://www.adyngom.com Ady Ngom
- http://blueco.ir/ طراحی سایت و سئو
