Update: here is a working demo of the project I was working on: http://www.newedenfaces.com
I have two views: PeopleView , in which there are 2 sketches (collection) and PersonView - each sketch (model).
This is basically a Facemash clone where you have two images side by side. If one of the players wins the game, the other will lose the game.
To update your winnings account, just add this to PersonView :
// Model View events: { 'click img': 'winner' }, winner: function() { this.model.set('wins', this.model.get('wins') + 1); this.model.save(); }
But how to update another model, increasing the number of losses? Or should I do this type of logic at the collection level, and not on a separate model?
Update
Until I find an elegant solution, I managed to solve this problem with this 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(); },
My PersonView is still processing the win count update. However, viewing the PeopleView collection listens for the event when updating the number of wins. When this happens, this model takes this position and gets its index position. Since I only have 2 views / 2 models, the other model should be the βloserβ. You get the index of another model through Math.abs(1 - winnerIndex) , and the only thing you need to do is update the loss counter.
Note I just started learning Backbone, so this is my first project using it. I really hope that there is a better way to do this. If you know, send an answer so that I can accept and close this question.