Skip to content

Instantly share code, notes, and snippets.

@mattheu
Last active December 16, 2015 13:39
Show Gist options
  • Save mattheu/5443478 to your computer and use it in GitHub Desktop.
Save mattheu/5443478 to your computer and use it in GitHub Desktop.
// I guess this is a question of best practice and JavaScript design patterns.
// I have an object, and have defined all my functions as properties on this.
// My problem...
// I want to attach a function within the object to a click event.
// As this was getting messy - I wanted to avoid using a closure, instead passing a callback function.
// However within that callback function, this referes to the clicked element.
// How do I access other properties on MyClass?
// What is the BEST way to do this? Am I trying to do something stupid.
var MyClass = {
prop : 'Foo',
init : function {
var t = this;
jQuery( document ).on( 'click', '.btn', t.myFunc );
}
muFunc : function(e) {
// How to get 'Foo'?
}
};
MyClass.init();
// Option 1
// Access MyClass.prop.
var MyClass = {
prop : 'Foo',
init : function () {
var t = this;
jQuery( document ).on( 'click', '.btn', t.myFunc );
},
myFunc : function( t, e, el ) {
e.preventDefault();
alert( MyClass.prop );
}
};
MyClass.init();
// Option 2
// Use a closure, and call t.myFunc there - passing t as param.
var MyClass = {
prop : 'Foo',
init : function () {
var t = this;
jQuery( document ).on( 'click', '.btn', function(e) {
t.myFunc( t, e, this );
} );
},
myFunc : function( t, e, el ) {
e.preventDefault();
alert( t.prop );
}
};
MyClass.init();
// Option 3
// Pass t as 'on' data param.
var MyClass = {
prop : 'Foo',
init : function () {
var t = this;
jQuery( document ).on( 'click', '.btn', { t : t }, t.myFunc );
},
myFunc : function( e ) {
e.preventDefault();
var t = e.data.t; // ref to MyClass passed as property on the event object.
alert( t.prop );
}
};
MyClass.init();
// Option 4
// Use call to set up the context of myFunc.
// This feels like it makes sense whithin this pattern as 'this' will refer to the class, rather than the clicked element.
// Is this really crazy?
var MyClass = {
prop : 'Foo',
init : function () {
var t = this;
jQuery( document ).on( 'click', '.btn', function(e) {
_this.myFunc.call( _this, e, this );
} );
},
myFunc : function( e, el ) {
e.preventDefault();
alert( this.prop );
}
};
MyClass.init();
// Option 5
// suck it up and use a closure?
// We can just access t directly as it is within the scope.
var MyClass = {
prop : 'Foo',
init : function () {
var t = this;
jQuery( document ).on( 'click', '.btn', function(e) {
e.preventDefault();
alert( t.prop );
} );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment