当我的Backbone应用程序的第一页加载时,我获取一个集合,然后迭代它以呈现页面:
页面路由器:
home: function ()
{
new BodyView ({page:'home'});
new HomeView();
new PostView();
postCollection = new PostCol({userId:getId(),start:0,offset:50});
postCollection.fetch();
postView = new Post({collection:postCollection});
},
发布视图:
el:'.stream',
initialize: function ()
{
this.collection.on('reset',this.render.bind(this));
this.collection.on ('change',this.render.bind (this));
},
render: function ()
{
this.collection.each (function (model)
{
actor = new Actor ({model:model});
this.$el.append (actor.render().el);
},this);
return this;
},
我现在要做的是当用户在另一个视图中保存一些数据时,它会更新Post视图。这就是我所做的,但它不起作用。
其他观点:
post = new PostModel ({userid:getId(),post:postText,objectid:0});
post.save({},
{
success: function (response)
{
postCol = new PostCol ({userId:getId(),start:0,offset:50});
postView = new Post ({collection:postCol});
postCol.fetch ().success({change:true});
},
error: function (response)
{
console.log (response);
}
}
);
答案 0 :(得分:1)
看起来postCollection
是全局的,因此您可以更新现有模型,而不是创建新模型。
// find existing model in the collection.
var post = postCollection.get(getId());
// save model with updated info.
post.save({post:postText},
{
success: function (response)
{
// if the save succeeded, the Post view will re-render,
// since you are listening for the 'change' event.
// so here, you don't really need to do anything.
},
error: function (response)
{
console.log (response);
}
);
而不是Post视图中的this.collection.on ('change',this.render.bind (this));
,您可以在单独的Actor视图中执行此操作,因此整个集合不会重新渲染。
this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind`