alexdmejias
alexdmejias

Reputation: 1419

Backbone returning length of 0

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

Answers (2)

Gokul Kav
Gokul Kav

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

CD..
CD..

Reputation: 74166

fetch performs an asynchronous HTTP (Ajax) request, so you should pass fetch a success callback:

collection.fetch({
   success: function(){
       console.log(collection.length);
   }
});

Upvotes: 4

Related Questions