Skip to content

Instantly share code, notes, and snippets.

@jpcody
Created March 16, 2012 13:04
Show Gist options
  • Save jpcody/2049998 to your computer and use it in GitHub Desktop.
Save jpcody/2049998 to your computer and use it in GitHub Desktop.
Maintaining an object and selector context with jQuery
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