Reputation: 1419
I'm fairly new to backbone and I'm trying to build a simple app. This is what I have so far
var Election = Backbone.Model.extend();
var Elections = Backbone.Collection.extend({
model: Election,
url: '/assets/data.json',
initialize: function() {
console.log('init col');
this.render();
return this;
},
render: function() {
console.log('rendering the collection');
return this;
},
// return this
});
var router = Backbone.Router.extend({
routes: {
'': 'root'
},
root: function(){
var collection = new Elections();
collection.fetch();
console.log(collection.length); //returns 0
}
});
var r = new router();
Backbone.history.start();
The log is this
> init col
> rendering the collection
> 0
But when I create a new collection manually in the console, it shows the right length and everything, I assume that for some reason the router call is happening too early, not sure though. This is a sample of data.json
[
{
"year": 1868,
...
},
{
"year": 1872,
...
},
Upvotes: 1
Views: 194
Reputation: 849
expanding on CD's answer a little bit,
a better approach would be calling fetch
and then using listenTo
to call the render
method on change
in your initialize method do this
_.bindAll(this, 'render');
this.listenTo(this, 'change', this.render);
and you can have the fetch outside if you wish
collection.fetch()
and it will automatically update on change
Upvotes: 0