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

Backbonejs - view initialize not show the collections

我正在尝试从本地 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();

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

render() 不会自动调用。

fetch() 不会触发 reset 事件,除非您通过 {reset: true}。您应该改为绑定到 sync 事件。

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

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