Skip to content

Instantly share code, notes, and snippets.

@iain
Created January 11, 2010 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain/274702 to your computer and use it in GitHub Desktop.
Save iain/274702 to your computer and use it in GitHub Desktop.
bind scopes to callbacks in jQuery
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