主干:渲染前获取
Backbone: Fetch before rendering
我想添加一个新项目到我的主干集合使用:
window.bearList.create({ name: "Tina" } );
这将正确地将新项目保存到服务器,因为之后我可以在服务器上看到它,这就是我想要的。(我正在使用MongoDB)
{"name":"Tina","_id":"53b41d92b7083d0b00000009","__v":0}
我在我的bearList ListView中有这个绑定:
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('add', this.render);
},
问题是,上面的代码只是将以下内容添加到我的集合视图中,直到我重新加载页面。
{"name":"Tina"}
我已经尝试使用model.save()回调,但我仍然有同样的问题。
就像我说的,服务器上的一切看起来都很好,一旦我重新加载页面,集合就会有更正版本的"Tina"。
但是由于某种原因,它没有得到ListView的'render'事件的完整模型。我试过在ListView渲染方法上单独抓取每个模型,但这不起作用,无论如何都是不好的做法。
有人能帮我一下吗?这是我的完整代码:
window.ListView = Backbone.View.extend({
tagName: 'ul',
className: 'list-group',
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('add', this.render);
},
render: function(){
this.$el.html(" ");
this.collection.each(function(item){
var listItemView = new ListItemView({ model: item });
this.$el.append(listItemView.render().el);
}, this);
return this;
},
});
window.ListItemView = Backbone.View.extend({
tagName: 'li',
className: 'list-group-item',
initialize:function () {
this.model.bind("change", this.render);
},
render:function () {
console.log(JSON.stringify(this.model.toJSON()));
this.$el.html("<a href='#"+ this.model.hashType + "/"+this.model.get('_id')+"' >" + this.model.get('name') + "</a>");
return this;
}
});
Just pass wait:true.
window.bearList.create({ name: "Tina" }, {wait: true} );
http://backbonejs.org/Collection-create
传递{wait: true}如果您想在添加之前等待服务器新模型的集合。
监听sync
事件,因为add
只会添加您在主干中创建的值。http://backbonejs.org/同步
还有一个提示:使用listenTo来使用Backbone的更多特性。而不是
initialize:function () {
this.model.bind("change", this.render);
},
使用:
initialize:function () {
this.listenTo( this.model, "change", this.render );
},
相关文章:
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- 主干-从模板中迭代的集合中获取特定的模型
- 获取结果未定义(主干.js)
- 所需响应的主干无限集合获取调用
- 主干:在变量中提供JSON,而不是通过URL获取
- 正在获取要在主干视图中使用的节点视图
- 主干.js更改模型的 url 参数,提取不会更新获取的数据
- 在主干提取完成后获取响应标头
- 主干模型通过ID获取JSON元素
- 使用add:true参数获取集合时,重新渲染主干视图
- 以正确的方式获取主干回调
- 从实例获取主干视图的父类
- 正在获取主干中的按钮值
- 在foreach循环中获取主干模型
- 获取主干模型错误
- 无法获取主干模型提取的结果
- 从远程url错误中获取主干集合
- CID无法获取主干集合中的模型
- 如何使用 Commonjs 在视图中获取主干应用程序文件变量
- 获取主干以提供静态 HTML 文件