Created
January 11, 2010 23:02
-
-
Save iain/274702 to your computer and use it in GitHub Desktop.
bind scopes to callbacks in jQuery
This file contains 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
var MyClass = new Function(); | |
MyClass.prototype = { | |
/** | |
* bind(Function) -> Function | |
* | |
* The problem with jQuery is that jQuery methods change +this+ inside their | |
* callbacks. This looses your reference to the current object. Pass the | |
* callback-function to +bind+ and it fixes it for you. | |
* | |
* Example: | |
* | |
* applyClick: function() { | |
* $('a.special').click(function(event) { | |
* this // -> dom element | |
* }); | |
* }, | |
* | |
* applyClick: function() { | |
* $('a.special').click(this.bind(function(event) { | |
* this // -> myClass instance | |
* })); | |
* }, | |
* | |
* applyClick: function() { | |
* $('a.special').click(this.bind(this.handleClick)); | |
* }, | |
* handleClick: function(event) { | |
* this // -> myClass instance | |
* }, | |
* | |
*/ | |
bind: function(funct) { | |
var context = this; | |
return function() { | |
return funct.apply(context, arguments); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment