Search code examples
jsonbackbone.jsbackbone-views

Backbonejs - view initialize not show the collections


I am trying to fetch the json objects from local json file. the file contains an array with 2 data.

my views initialize method not giving any result.

what i the mistake I made here? any one help me?

here is my code :

var Theater = {
    Models: {},
    Collections: {},
    Views: {},
    Templates:{}
}

Theater.Models.Movie = Backbone.Model.extend({});

Theater.Collections.Movies = Backbone.Collection.extend({
    model: Theater.Models.Movie,
    url: "scripts/data/movies.json",
    initialize: function(){
        console.log("Movies initialize");
    }
});

Theater.Views.Movies = Backbone.View.extend({
    initialize: function () {
        console.log( 'view', this.collection, this.collection.models.length ) //gives  no results
        _.bindAll(this, "render");
         this.collection.bind("reset", this.render);
    },

    render: function(){
        console.log("render") 
        console.log(this.collection.length); nothing consoled
    }
})

Theater.Router = Backbone.Router.extend({
    routes: {
        "": "defaultRoute"
    },

    defaultRoute: function () {
    console.log("defaultRoute");
    Theater.movies = new Theater.Collections.Movies()
    new Theater.Views.Movies({ collection: Theater.movies }); 
    Theater.movies.fetch().done(function(){
        console.log(Theater.movies.length) //2
    });

}
})

var appRouter = new Theater.Router();
Backbone.history.start();

Solution

  • fetch() won't trigger reset event unless you pass {reset: true}. You should bind to sync event instead.

    And it is a good idea to use listenTo for binding events:

    this.listenTo(this.collection, 'sync', this.render);