Search code examples
backbone.js

calling another function from backbone.js fetch success


I am trying to call another function on success of the fetch in the first function but I keep getting an undefined error. The console.log('success') is working.

In the view:

secondFunction: function() {
  console.log('second function called');
},

someFunction: function() {
  someData.fetch({
    success: function(results) {
      console.log('success');
      this.secondFunction();
    }
  });
 },

When I do it like this it's fine but I need the secondFunction to wait until the success of the first for the data.

secondFunction: function() {
  console.log('second function called');
},

someFunction: function() {
  someData.fetch({
    success: function(results) {
      console.log('success');
    }
  });
  this.secondFunction();
 },

Solution

  • try:

    someFunction: function() {
      var self = this;
      someData.fetch({
        success: function(results) {
          console.log('success');
          self.secondFunction();
        }
      });
     },
    

    Note the use of self. Keep in mind you are in the callback function ;-)