0

Consider a RESTful API that returns the following in it's typical response

  • List of results
  • Pagination information
  • Navigators (i.e. Categories, Sub-Categories, Locations, etc.)
  • Graphing data

In the View, every time a navigator is changed, the results, graphs, and navigators must be updated.

I would like to have a single fetch() that will update all of these collections.

I have been able to do this already, but it is not clean and I am looking for a best-practice to handle this, since I would expect this to be a common scenario. Yet, I have not been able to find much on this.

I will note that I am using Backgrid JS (if that is relevant for the answer).

Maybe I am not searching for the right terms, but I would appreciate any help with this.

Thanks!

chaimp
  • 16,897
  • 16
  • 53
  • 86
  • 1
    if i were you i would parse API in controller , on success i would parse response and reset collections and models with proper part of response. – Evgeniy Sep 04 '14 at 07:58
  • That makes sense. Is there some best-practice for such a controller (i.e. to wrap inside a Backbone.Model)? Or would some generic jquery ajax calls suffice? My goal of refactoring is to make it cleaner. – chaimp Sep 04 '14 at 08:26
  • 1
    Basing on my experience i can recommend you to look closely at Backbone Marionette. It already has such abstractions as Application , Controller that can be useful in Backbone application refactoring. If you don't mind use it, it will be you magic wand in such situations – Evgeniy Sep 04 '14 at 08:35

1 Answers1

0

The approach we took was to have models with nested collections in them. In our approach a model looks something like this:

var MyModel = Backbone.Model.extend({
  nested : [
  {
    name: 'childCollection1',
    Collection: Backbone.Collection
  },
  {
    name: 'childCollection2',
    Collection: Backbone.Collection
  }
  ]
});

The nested collections are instantiated as Collections in initialize. Data is retrieved from the server in a single fetch, the nested collections are reset with the fetched data in parse(), and converted back to arrays in toJSON().

Here's a gist: https://gist.github.com/christinedraper/8cc160b4424a16828714