Oskar Szura
Oskar Szura

Reputation: 2549

Loading model or collection

I'm new to Backbone and I was using ExtJS before. My goal is to populate a Backbone collection with some data. Now... in ExtJS if I wanted to load a collection than I was using the .load() method that belonged to it. As I'm reading Backbone's documentation I can see that there are mostly feching / syncing methods assigned to 'models'. So my question is:

"If I want to load a Backbone's collection, should I load it directly or via 'model'?"

Upvotes: 1

Views: 62

Answers (1)

trenpixster
trenpixster

Reputation: 390

A Backbone Collection can be a collection of Backbone Models. If you set your collection as:

YourCollection = Backbone.Collection.extend({
    model: YourModel,
    url: '/url/to/json/collection';
    }
});

and your model as:

YourModel = Backbone.Model.extend({
    url: '/url/to/json/model';
    }
});

Then you can do something like:

var collection = new YourCollection();
collection.fetch(); //GETs /url/to/json/collection

The path /url/to/json/collection should return a JSON array where each element in the array would be the JSON for your Models.

The path /url/to/json/model should return a JSON representing one Model.

Imagining your server returned JSON has a property like "name", then you can do interesting stuff: collection.where({name: 'some name'}). This would return an array with YourModels.

So, answering your initial question, yes you should load it via Backbone's collection.

Upvotes: 2

Related Questions