Reputation: 72001
I've got lots of code that does stuff like the following to bind a callback to this
:
someMethod: function()
{
this.doSomething({
callback: function(a,b,c)
{
console.log(a);
console.log(this.title);
}.bind(this),
otherData: [1,2,3,4],
anotherOption: true
});
}
title:'test',
I'd like this to be more readable, and encapsulate how I do my binding to this - through a function call or something similar... something like the following pseudocode (which I know wouldn't work):
someMethod: function()
{
this.doSomething({
callback: this.bind(a,b,c)
{
console.log(a);
console.log(this.title);
},
otherData: [1,2,3,4],
anotherOption: true
});
},
title:'test',
Is there anyway to bind a callback to this that's more readable? Note that my example above is simplified - often I might have 2 callbacks being passed in, as well as other options as well.
Upvotes: 0
Views: 78
Reputation: 122906
I think you can also use something like:
//...
someMethod: function() {
this.doSomething({
boundTo: this, //<= here
callback: function(a,b,c) {
console.log(a);
console.log(this.boundTo.title); //<= and here
},
otherData: [1,2,3,4],
anotherOption: true
})
}
// ...
Or this (closure) should work too
someMethod: function() {
this.doSomething({
callback: function(self) {
return function(a,b,c) {
console.log(a);
console.log(self.title);
};
}(this),
otherData: [1,2,3,4],
anotherOption: true
});
}
Upvotes: 1
Reputation: 10874
Personally I would create the callback method then assign it, I find it less painful to read and if needed it also leave you a reference of the function which can be useful when using bind
with event handlers for example (can add/remove them) as bind
returns a function.
someMethod: function() {
var callback = function(a,b,c) {
console.log(a);
console.log(this.title);
}.bind(this);
this.doSomething({
callback: callback
});
},
title:'test',
You could also not use bind
at all and like many JS methods take an argument which is the scope of your callback so basically just adding a new property to your object scope: this
. Ideally callback should be run using call
which take the scope as first argument.
Upvotes: 3
Reputation: 6167
How about:
someMethod : function ()
{
var that = this;
this.doSomething({
callback : function (a,b,c) {
console.log(a);
console.log(that);
}
});
}
There is no need for .bind
if you are creating a new function each time anyway. Local variables are more suitable here.
Upvotes: 1