【问题标题】:Backbonejs - view initialize not show the collectionsBackbonejs - 视图初始化不显示集合
【发布时间】:2017-03-21 06:56:31
【问题描述】:

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

【问题讨论】:

    标签: json backbone.js backbone-views


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      render() 不会被自动调用。

      【讨论】:

      • 但是我打电话给reset 它应该对我有用,请参阅:this.collection.bind("reset", this.render);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2011-12-08
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多