fdot
fdot

Reputation: 405

Backbone fetch success callback

I'm new to backbone.js and I'm having some issues with giving my collection a success callback. I'm overriding fetch in order to have a url with a parameter in it. As I understand it I should be able to assign a success callback in the options I pass to Backbone.Collection.prototype.fetch.call()... but, my code isn't working. Fetch works correctly, but the callback function is not called.

Here is a bit of my code:

App.ChartController = {
  load: function(userConceptId) {
    App.chartPointList.fetch(userConceptId);    
  }
};


App.ChartPointList = Backbone.Collection.extend({
  model: App.ChartPoint,
  url: function() {
    return '/chartpoints/' + this.userConceptId;
  },
  fetch: function(userConceptId, options) {         
    console.log("fetch chart point");               

    typeof(options) != 'undefined' || (options = {});
    options.success = this.postProcess;
    options.error = this.handleError;

    this.userConceptId = userConceptId;

    return Backbone.Collection.prototype.fetch.call(this, options);    
  },
  postProcess : function (resp, status, xhr) {
    console.log("postprocess");          // never gets called
    /**
     ... whole bunch of stuff... 
    **/
    new App.Views.ChartView({ collection: this });
  }, 
  handleError : function (resp, status, xhr) {
    alert("could not load chart data!");  // also not called
  }
});

Any idea what I'm doing wrong? Thanks!

Upvotes: 3

Views: 10972

Answers (1)

fdot
fdot

Reputation: 405

@fguillen's comment and another SO thread helped me figure this out. Specifically:

Collection.fetch() will call reset() on success, which in turn will trigger a 'reset' event. Any subscribers to the collections reset event should receive the event.

The issue wasn't with my success callback at all. Turns out I had an problem in a view that was subscribed to the ChartPointList reset event. A function in that view was being called before the success callback and throwing an error, and thus the success callback was not being called.

Upvotes: 4

Related Questions