我正在使用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
});
});
据我所知,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."
}
]
答案 0 :(得分:10)
您的代码存在两个潜在问题。
事件监听器回调应该在调用collection.fetch()
之前注册。否则,您可能会错过第一个reset
事件,因为它可能会在注册侦听器之前触发。
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 } });
注意如何通过用空格分隔来从同一个对象注册多个事件。
答案 1 :(得分:2)
变化
this.collection.bind('reset', this.render, this);
到
this.collection.bind('sync', this.render, this);
问题是您在开始时只执行一次重置。那时你没有任何东西可以渲染。下次,当您获取集合时,重置事件不会触发,因为您在没有选项{reset:true}的情况下获取集合。
答案 2 :(得分:1)
更改此行
this.collection.bind('reset', this.render, this);
到
this.listenTo(this.collection, 'reset', this.render);
答案 3 :(得分:0)
获取集合时,默认情况下不会再触发重置事件。 (我相信自1.0版本) 为了让Backbone在获取集合时触发重置事件,你现在必须像这样调用fetch方法:
this.collection.fetch({reset: true});