Mina Wissa
Mina Wissa

Reputation: 10971

Backbone JS: self populate Collection

I have a Backbone collection like this

var ContactsCollection = Backbone.Collection.extend({
    model: Contact,

    initialize: function () {
            //retrieves contacts from web service
            //contactsLoaded: is the callback that gets called after 
            //the contacts get received
            loadContacts(this.contactsLoaded);
    },

    contactsLoaded: function (contacts) {
            for (var i = 0; i < contacts.length; i++) {
              //TODO populate the collection [models][1]
            }
    }
});

in other word, I want to self populate the collection's models, how can I do this ?

Upvotes: 2

Views: 2093

Answers (4)

yujingz
yujingz

Reputation: 2389

For a Backbone collection, you needn't to add the model one by one, the framework will do the job. Simply

var ContactsCollection = Backbone.Collection.extend({
  model: Contact,
  url: '/contacts' // whatever web service url you are using

  initialize: function () {
    this.fetch();
  }

});

If your return from the server is not an JSON array, or it's wrapped with some node, you can override the parse method.

parse: function(response) {
  // if it's like {data: [model1, model2, model3...]}
  return response.data
}

Upvotes: 1

Scott Puleo
Scott Puleo

Reputation: 3684

Agree with @Loamhoof. You should use backbones fetch to accomplish this.

I suggest you move the call to fetch outside the collections initialize method. It would be clearer and more handy to put it with the rest of your applications control flow / router logic. Fetch will return a jqXHR object implements a promise interface. Allowing you to do something like this:

var contactsCollection = new ContactsCollection({});
var p = contactsCollection.fetch();

p.done(function() { ... });
p.error(function() { ... });
p.always(function() { ... });

Upvotes: 0

Loamhoof
Loamhoof

Reputation: 8293

Consider using the REST API as Collection#fetch should do exactly what you want.

var ContactsCollection = Backbone.Collection.extend({
model: Contact,
url: '', // set the URL
initialize: function () {
  this.fetch();
}});

Upvotes: 2

Cianan Sims
Cianan Sims

Reputation: 3429

Assuming you're passing in a list of contact models, do this (you don't need a for loop):

this.add(contacts);

The docs mention you can add models one by one, or as an array.

Upvotes: 0

Related Questions