3

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!

fdot
  • 405
  • 1
  • 5
  • 11
  • The _error callback_ works for me: http://jsfiddle.net/fguillen/vsZUD/ , so the problem should be somewhere else. – fguillen Jun 04 '12 at 17:58

1 Answers1

4

@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.

Community
  • 1
  • 1
fdot
  • 405
  • 1
  • 5
  • 11
  • Awesome — listening to "reset" works perfectly. Also [this SO thread](http://stackoverflow.com/questions/6659283/backbone-js-fetch-with-parameters) helped me pass parameters to specific fetch without modifying the collection's url or fetch. – Warpling Jul 19 '13 at 22:47