更新:这是我正在处理的项目的工作演示:http://www.newedenfaces.com
我有两个 View :PeopleView 包含 2 个缩略图(集合)和 PersonView - 每个缩略图本身(模型)。
这基本上是一个 Facemash 克隆,其中有两个并排的图像。如果一个人赢了比赛,另一个人输了比赛。
要更新 wins count,很简单,只需将其添加到 PersonView:
// Model View
events: {
'click img': 'winner'
},
winner: function() {
this.model.set('wins', this.model.get('wins') + 1);
this.model.save();
}
但是我如何通过增加损失计数来更新另一个模型?或者我应该在集合级别而不是在单个模型上执行这种类型的逻辑吗?
更新
在我找到一个优雅的解决方案之前,我已经设法使用这个 hack 解决了这个问题:
// Collection View
initialize: function() {
this.collection.on('change:wins', this.updateLosses, this);
},
updateLosses: function(model) {
var winnerIndex = this.collection.indexOf(model);
var otherModel = this.collection.at(Math.abs(1 - winnerIndex));
otherModel.set('losses', otherModel.get('losses') + 1);
otherModel.save();
this.render();
},
我的 PersonView 仍在处理获胜计数的更新。但是,PeopleView Collection View 会在更新获胜计数时监听该事件。当发生这种情况时,它采用该模型并获得其索引位置。因为我只有 2 个 View /2 个模型,所以另一个模型一定是“失败者”。您可以通过 Math.abs(1 - winnerIndex)
获取另一个模型的索引,您唯一需要做的就是更新其损失计数。
注意:我刚刚开始学习 Backbone,所以这是我使用它的第一个项目。 我真的希望有更好的方法来做到这一点。如果您知道,请发布答案,以便我接受并关闭这个问题。
最佳答案
与@pvnarula 的回答类似,您可以使用 Backbone 的内置 Event模块 创建模型 View 绑定(bind)到的事件调度程序。
// Define an event dispatcher/handler
var dispatcher = _.extend({}, Backbone.Events);
// Model View
initialize: {
this.listenTo(dispatcher, 'game:over', this.updateCounts);
}
events: {
'click img': 'winner'
},
winner: function() {
// just trigger the custom event and let each view figure out how to respond.
// also pass along the id of the winning model
dispatcher.trigger('game:over', this.model.id)
},
updateCounts: function(winnerId) {
if (this.model.id === winnerId) {
this.model.set('wins', this.model.get('wins') + 1);
} else {
this.model.set('losses', this.model.get('losses') + 1);
}
this.model.save();
}
还值得查看这篇文章以了解有关主干事件的更多信息:http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/
关于javascript - 如何从 Backbone.js 中的集合中的另一个模型触发模型更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16992400/