Search code examples
backbone.js

unable to call fetch on a backbone model


In the function jsonRequest below, I can log this.model to the console, but I can't call this.model.fetch(), which I thought was the appropriate way to make a request to my server (at localhost:8080/jsonapi). The error it gives me is can't call fetch of undefined. Is there something I'm doing wrong in the code below?

var MyModel = Backbone.Model.extend({
      url: 'jsonapi',
});

var MyView = Backbone.View.extend({
        el: '#blahblah',
        initialize: function(){

        },
        events: {
                'click #start' : 'callJsonRequest',

        },
        callJsonRequest: function(){
              setInterval(this.jsonRequest, 1000);
        }, 

        jsonRequest: function(){
                         console.log("jsonrequest", this.model); //this logs the model
                         this.model.fetch();
                     },

  });

    window.myModel = new MyModel();
    window.startStop = new StartView({model: myModel});

Solution

  • You likely need to use bind to make sure this is the context of your View object.

    As you mentioned in the comments, you can do:

    setInterval(this.jsonRequest.bind(this), 1000);