Search code examples
javabackbone.jsjax-rsbackbone.js-collections

Populate Backbone View with multiple Collections


I am new to Backbone.

I am looking a design pattern that work for my situation.

Currently I have a View template which consist of multiple html select:

<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
....

And going to populate the select with multiple Backbone Collections, with different JAX-RS API path.

var C1 = Backbone.Collection.extend({
    url='/path1'
});

var C2 = Backbone.Collection.extend({
    url='/path2'
});

...

A straight forward way, is to have a solution like this:

render: function(){
    var that = this, promises = [], 
        c1 = new C1(), c2 = new C2(), c3 = new C3();

    promises.push(c1.fetch());
    promises.push(c2.fetch());
    promises.push(c3.fetch());
    ...

    $.when.apply(null, promises).done(function(){
        that.$el.html(FormTemplate({c1m: c1.models, c2m: c2.models, c3m: c3.models, ...}));
    });

    return this;
}

However, this will involve several API calls from the client to the Java server. Is there any way I can achieve this using only 1 API call?

Thanks.


Solution

  • Obviously the API should provide a single route that returns all data. Then you can fetch it using single collection, and pass filtered data to other collections without them having to make API calls.

    Something like:

    var SingleEndPointCollection = Backbone.Collection.extend({
      url = '/singleEndPoint'
    });
    
    var C1 = Backbone.Collection.extend({});
    
    var C2 = Backbone.Collection.extend({});
    
    var C3 = Backbone.Collection.extend({});
    
    var view = Backbone.View.extend({
      initialize: function() {
        var that = this;
        this.collection = new SingleEndPointCollection();
        this.collection.fetch({
          success: function(collection, response) {
            that.c1 = new C1(collection.filter(function() {
              // your logic here
            }));
            that.c2 = new C2(collection.filter(function() {
              // your logic here
            }));
            that.c3 = new C3(collection.filter(function() {
              // your logic here
            }));
            that.render();
          }
        });
      },
      render: function() {
        var that = this;
        that.$el.html(FormTemplate({
          c1m: that.c1.toJSON(),
          c2m: that.c2.toJSON(),
          c3m: that.c3.toJSON()
        }));
        return this;
      }
    });