0

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()  });
  • Tried this already `this.on("change", () => {...})`? – Sayan Pal May 18 '17 at 20:40
  • 1
    As said in mu's answer, use `listenTo` and `_.bindAll` becomes useless. [Avoid `this.on` as it's the old way of binding events and can leak memory](http://stackoverflow.com/questions/16823746/backbone-js-listento-vs-on). – Emile Bergeron May 18 '17 at 21:35
  • 1
    @SayanPal - er, no. It worked. Don't know how I missed that. Thanks. –  May 22 '17 at 19:15

1 Answers1

1

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • this.on("change", this.calculatePrice, this ); worked but bearing in mind @Emile Bergeron's comments I've gone with: this.listenTo(this, "change", this.calculatePrice) ; --- I thought that listenTo was only for other objects but it seems to work used like this. As you say _.bindAll was redundant in either case. –  May 22 '17 at 19:36
  • `a.listenTo(b, ev, f)` is pretty much `b.on(ev, f)` with some extra house keeping to keep track of `this` and what events are bound. You should be able to convert any `on` call to a `listenTo`. – mu is too short May 22 '17 at 23:25