Backbonejs - 视图初始化不显示集合

时间:2017-03-21 06:56:32

标签: json backbone.js backbone-views

我正在尝试从本地json文件中获取json个对象。该文件包含一个包含2个数据的数组。

我的观点initialize方法没有给出任何结果。

我在这里犯的错误是什么?任何人帮助我?

这是我的代码:

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();

2 个答案:

答案 0 :(得分:2)

除非您通过fetch(),否则

reset不会触发{reset: true}事件。您应该绑定到sync事件。

使用listenTo绑定事件是个好主意:

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

答案 1 :(得分:-1)

您必须将this.render();放入initialize: function () {}

render()不会自动调用。