0

I have the following Backbone View with a render function that looks like the following:

render: function () {
this.emptyContent();
    if (this.model.get('ChatsInQueue') == -1) {
        this.model.set('ChatsInQueue', '-');
    }
    this.$el.append(this.template({ Stats: this.model.toJSON(), Prior: this.model.get('PriorDayStats') }));

    var self = this;
    this.graphView.model.fetch({

        success: function () {
            self.graphView.render(this.model.get("TotalCalls"), this.model.get("CallsAbandoned"));
        }
    });  
 this.tickerTapeText();
    $(window).trigger('resize');

However, when I run the application, I receive the following console error:

Uncaught TypeError: Cannot read property 'get' of undefined
at success

Can someone help me diagnose what about my success function needs changed so that 'get' is defined?

SamRR_75
  • 729
  • 8
  • 18

1 Answers1

1

JavaScript's function binds its own this which is different from the this of the context it's created in. In ES6, arrow functions were introduced as an alternative to a function that doesn't bind its own this (among others, see the MDN web docs).

You already worked around that by declaring a variable self and assigning this to it and used it for the self.graphView.render call. However, in the parameters, you still used this instead of self. Use self there, too, or even better use arrow functions if your environment implements them. Current browsers should already support them.

Thunderbolt
  • 433
  • 3
  • 5
  • So obvious! Thanks! – SamRR_75 Jul 24 '19 at 18:45
  • I received the same error for the following code: _.each(this.model, function (client) { this.createGraphData(client.get("TotalCalls"),client.get("CallsAbandoned")); }); Any thoughts? – SamRR_75 Jul 24 '19 at 19:33
  • 1
    Yeah, that's the same case (see `this.createGraphData`). `this` inside of a `function` will be a different `this`. Capture the outer `this` again with a `self`-variable or use arrow functions. – Thunderbolt Jul 24 '19 at 19:41
  • I have this, which isn't working: var self = this; _.each(self.model, function (client) { self.createGraphData(client.get(totalCalls), client.get(callsAbandoned)); – SamRR_75 Jul 24 '19 at 19:47
  • would you be willing to code out your potential solution? – SamRR_75 Jul 24 '19 at 20:00
  • What's the concrete error message for your sample? I believe there must be something wrong in `totalCalls` and/or `callsAbandoned` since your sample seems to be ok if the closing `});` was be there. – Thunderbolt Jul 24 '19 at 20:02
  • Uncaught TypeError: Cannot read property 'get' of undefined – SamRR_75 Jul 24 '19 at 20:05
  • Is there actual data in the `this.model`-array that contains a get-function for every element? – Thunderbolt Jul 24 '19 at 20:07
  • I managed to resolve the error by using a backbone each method instead of using underscore. Thanks for the help! – SamRR_75 Jul 24 '19 at 20:22