Mirza Delic
Mirza Delic

Reputation: 4339

backbone why using model in collection

why use model inside collection, can someone explain me?

Example:

var model = Backbone.Model.extend({
  url: '/rest/article/'
});

var collection = Backbone.Collection.extend({
  url: '/rest/article',
  model: model
});

Upvotes: 0

Views: 57

Answers (2)

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14225

var model = Backbone.Model.extend({
  parse : function (response) {
    // you can modify model
    response.author || (response.author = 'Anonymous');
    return response;
  },
  getArticleTitle : function () {
    return this.get('author') + ' - ' + this.get('title');
  }
});

var collection = Backbone.Collection.extend({
  url: '/rest/article',
  model: model
});

// you can access model methods
collection.at(0).getArticleTitle();

Upvotes: 1

Decoy
Decoy

Reputation: 550

So whenever you add an item to the collection it can be instantiated as that kind of model.

Upvotes: 1

Related Questions