Backbone.js:获取模型集合并渲染它们

hyd*_*yde 15 javascript json backbone.js backbone-views

我正在使用Backbone.js学习JavaScript MVC应用程序开发,并且在视图中渲染模型集合时遇到问题.这就是我想要做的事情:

  • 页面完成加载后,从服务器检索数据作为模型集合

  • 在视图中渲染它们

这就是我想做的一切,这就是我到目前为止所做的一切:

$(function(){

    "use strict";

    var PostModel = Backbone.Model.extend({});

    var PostCollection = Backbone.Collection.extend({
        model: PostModel,
        url: 'post_action.php'
    });

    var PostView = Backbone.View.extend({
        el: "#posts-editor",        

        initialize: function(){
            this.template = _.template($("#ptpl").html());
            this.collection.fetch({data:{fetch:true, type:"post", page:1}});
            this.collection.bind('reset', this.render, this);
        },

        render: function(){
            var renderedContent = this.collection.toJSON();
            console.log(renderedContent);
            $(this.el).html(renderedContent);
            return this;
        }
    });

    var postList = new PostCollection();
    postList.reset();
    var postView = new PostView({
        collection: postList
    });

});
Run Code Online (Sandbox Code Playgroud)

问题

据我所知,Chrome正在记录来自服务器的响应,并且它是JSON格式,就像我想要的那样.但它并没有在我看来呈现.控制台中没有明显的错误.

服务器有一个处理程序,它接受GET参数并回显一些JSON: http://localhost/blog/post_action.php?fetch=true&type=post&page=1

[
   {
      "username":"admin",
      "id":"2",
      "title":"Second",
      "commentable":"0",
      "body":"This is the second post."
   },
   {
      "username":"admin",
      "id":"1",
      "title":"Welcome!",
      "commentable":"1",
      "body":"Hello there! welcome to my blog."
   }
]
Run Code Online (Sandbox Code Playgroud)

mor*_*mor 11

您的代码有2个潜在问题.

  1. 调用之前注册事件侦听器回调collection.fetch().否则,您可能会错过第一个reset事件,因为它可能会在注册侦听器之前触发.

  2. reset事件不足以确保每次更新集合时视图都将重新呈现.

另请注意,使用object.listenTo()表单绑定事件是一个好习惯,因为它将确保在关闭视图时正确取消注册.否则,你最终可能会被称为Backbone zombies.这是一个解决方案.

this.listenTo( this.collection, 'reset add change remove', this.render, this );
this.collection.fetch({ data: { fetch:true, type:"post", page:1 } });
Run Code Online (Sandbox Code Playgroud)

请注意如何通过用空格分隔来从同一对象注册多个事件.