Reputation: 561
I am using bind to change the scope of 'this' so that I am able to reference my generateContent function using 'this', from within my click function. Unfortunately this means that this.id no longer works as the scope of 'this' has changed.
What is the best way to grab the id of the clicked button, in this case:
function help( doc ) {
buttons: function() {
$('.add-btn').click( function() {
this.generateContent( this.id ) );
}.bind(this));
},
generateContent: function ( id ){
}
}
// This function binds a function to an object's scope.
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
Upvotes: 2
Views: 1430
Reputation: 140230
You didn't tag jQuery but your code quacks like jQuery so I'm assuming jQuery.
jQuery provides event.currentTarget
:
$('.add-btn').click( function(e) {
this.generateContent( e.currentTarget.id ) ;
}.bind(this));
Btw Function.prototype.bind
exists natively, you don't want to overwrite it in the cases where the native version is available. jQuery also provides $.proxy
, so you don't need it in any case.
Upvotes: 5