Reputation: 4077
I have a question with regards to the Bind feature in Underscore.js let’s say we have the following object "room":
var person = 'Bob';
$(function () {
var room = {
capacity: 10,
exits: 2,
count: 0,
person: '',
addPerson: function (name) {
this.count += 1;
var nestedFunction = function (nameOfPerson) {
// this is bound to window
this.person = nameOfPerson;
}(name);
}
};
room.addPerson('dave');
});
At the line indicated by my comment, "this" is bound to the window. That is expected behaviour.
Let’s say we want to bind it to the "room" object. Is it possible to do that with Underscore.js' bind method.
Note: I am aware I could handle this with the good old "that = this" routine. But I'm not interested in that.
Upvotes: 3
Views: 696
Reputation: 2485
I know this might not help for the question but I stumbled on this question in regards to backbone.
I was trying to save one model then another on the call back. He is the working end result. But _.bind could be used in any other function you cant access this on.
this.information.set('name', 'Bob');
this.information.save(null,
{
success: _.bind(function(model, response)
{
console.log('Saved Information');
this.review.set('review', "This is a test Review");
this.review.save(null,
{
success: function(model, response)
{
console.log('Saved Review');
location.reload();
}
});
}, this)
});
Upvotes: 0
Reputation: 1638
Yes, you can definitely do this using Underscore's bind.
You can use bind this way:
CODE:
var nestedFunction = _.bind(function (nameOfPerson) {
this.person = nameOfPerson;
},this);
Please take note of the this
passed as a second argument to bind
, which makes this
refer to what you want and not window
.
You can also do this without Underscore's bind by using call.
CODE:
addPerson: function (name) {
this.count += 1;
var nestedFunction = function (nameOfPerson) {
this.person = nameOfPerson;
};
nestedFunction.call(this,'dave');
}
Upvotes: 3