Created
March 16, 2012 13:04
-
-
Save jpcody/2049998 to your computer and use it in GitHub Desktop.
Maintaining an object and selector context with 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 object = { | |
handler : function(){ | |
$("selector").on( "click", _.bind( this.doSomething, this )); | |
}, | |
doSomething : function(e){ | |
// want this to be the object instead of the element we're acting on, | |
// so this.doSomethingElse will properly evaluate. but now if I want to | |
// access $(this), I'm hosed because the context is the object, not the element. | |
this.doSomething( $(this) ); | |
}, | |
doSomethingElse : function( $trigger ){} | |
}; | |
var object = { | |
handler : function(){ | |
$("selector").on( "click", { context : this }, this.doSomething ); | |
}, | |
doSomething : function(e){ | |
// it's a bit hacky, but now self contains the previous context, passed as | |
// arbitrary data on the event handler, and `this` contains the element that | |
// we're acting on, so we have access to both. | |
var self = e.data.context; | |
self.doSomething( $(this) ); | |
}, | |
doSomethingElse : function( $trigger ){} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment