当我的 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;
},
我现在想要完成的是,当用户在另一个 View 中保存一些数据时,它会更新“发布” View 。这就是我所做的,但它不起作用。
其他 View :
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);
}
}
);
最佳答案
看起来您的 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);
}
);
您可以在单个 Actor View 中执行此操作,而不是在 Post View 中使用 this.collection.on ('change',this.render.bind (this));
集合不会重新渲染。
this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind`
关于javascript - 当集合更改时更新主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939572/