Search code examples
javascriptbackbone.js

Backbone js building a collection from the results returned from multiple URL's


I have a model that looks like this:

var BasicModel = Backbone.Model.extend({
defaults: {
    a: '',
    b: '',
    c: '',
    d: '',
    e: ''
},
idAttribute: "f",
parse: function (data) {
    return data;
},
initialize: function () {
    console.log('Intialized');
},
constructor: function (attributes, options) {
    Backbone.Model.apply(this, arguments);
}
});

Collections like this:

var BasicCollection = Backbone.Collection.extend({
   model: BasicModel,
   url: urlCode
});

var ACollection = BasicCollection.extend({
   parse: function (data) {
       return data.a.b.c.d;
   }
});

var aCollection = new ACollection ();

And Views like this:

var BasicView = Backbone.View.extend({

   tagName: 'tr',

   template: _.template($('#basic-status-template').html()),

   render: function () {
       this.$el.html(this.template(this.model.attributes));
       return this;
   }

});

var BasicsView = Backbone.View.extend({

   initialize: function () {
       this.render();
   },

});

This is how the collection fetch looks (Which builds the views):

aCollection.fetch({
   success: function () {

       // View

       var aView = BasicsView.extend({
           el: '#foobar #table-body',

           render: function () {
               this.$el.html('');
               aCollection.each(function (model) {
                   var x = new BasicView({
                       model: model
                   });
                   this.$el.append(x.render().el);
               }.bind(this));

               return this;
           }

       });

       var app = new aView();
   }
});

But now I face a problem when trying to add another piece of detail to the tables that the views will populate. One of the columns will require data that will come from a seperate url. But I still want it to be part of the same process.

Is there are way to form a collection from the result of two URL's. (i.e. a, b, d and e come from URL 1, and c comes from URL 2)?

This way all I would need to change was the template and it should all work the same. Instead of having to alter a load of other stuff as well.

Thanks.


Solution

  • You have few options:

    1. Update the endpoint to send required data. This is the proper way to do it. Collection should Ideally have single endpoint

    2. Send a seperate AJAX request to get data from one URL before fetching collection, then in collection's parse method add the data to the response fetched from collection's URL

    3. Do something like:

      $.when(collection.fetch(), collection.fetchExtraData())
            .done(()=> { /* create view here */ });
      

      fetchExtraData here is a custom function that sends extra request and updates collection properly with the data. This way both requests are sent simultaneously. You need to make sure parse doesn't reset the data from other endpoint.