Reputation:
This is in a BackBone Model:
calculatePrice() {
}
initialize() {
_.bindAll(this, 'caclulatePrice');
this.on("change", function() {
this.calculatePrice();
});
}
The problem is when this compiles the inner this is just this and not the _this which is actually the model.
Having looked around (and based on similar cases in CoffeeScript) it looks like the answer is something to do with => But I can't make this work e.g
this.on("change", function() => {
doesn't compile.
What do I need to do to make the inner this refer to the BackBone model (the class it is in)?
Update:
This works but it can't be the 'right' way.
let that = this;
this.on("change", function() { that.caclulatePrice() });
Upvotes: 0
Views: 36
Reputation: 434785
You're binding the desired this
to the calculatePrice
function:
_.bindAll(this, 'calculatePrice'); // I'm assuming that 'caclulatePrice' is a typo...
not the anonymous function you're handing to this.on
.
A better way is to drop the _.bindAll
and supply the desired this
in the third argument to on
:
this.on('change', this.calculatePrice, this);
Or, if you really want to use _.bindAll
, just drop the anonymous function:
_.bindAll(this, 'calculatePrice');
this.on('change', this.calculatePrice);
You could also use listenTo
which will set the appropriate this
for you.
Upvotes: 1