javascript - Backbone.js: Existing View events continue to fire -
in view, have events fire onclick
of element. unfortunately, when create new view model, existing events of first model/view pair continue fire. ends happening save()
continues use existing model instead of new 1 , can never create new model , use model without refreshing page. i'm new backbone.js, there way save()
existing model remove view? if i'm not making sense, please let me know.
any appreciated! much.
$(function() { var game = backbone.model.extend({ defaults: { begun: false, currentplayer: 1 }, play: function() { console.log(this.id); var player = (this.get('currentplayer') == 1) ? 2 : 1; this.save({ 'currentplayer': player, 'begun': true }); } }); var gamelist = backbone.collection.extend({ model: game, localstorage: new store('game'), existing: function() { return this.filter(function(game){ return game.get('begun'); }); }, unused: function() { return this.filter(function(game){ return !game.get('begun'); }); } }); var games = new gamelist; var gameview = backbone.view.extend({ el: $('#board'), events: { 'click li a': 'play' }, initialize: function() { _.bindall(this, 'clear'); this.model.bind('destroy', this.clear); }, render: function() { console.log(this.model.id); this.clear(); }, clear: function() { this.el.find('li span').html(''); }, play: function(event) { $(event.currenttarget).find('span').html(this.model.get('currentplayer')); this.model.play(); return false; } }); var appview = backbone.view.extend({ el: $('#info'), events: { 'click #new-game': 'newgame' }, initialize: function() { _.bindall(this, 'startgame', 'getgame'); games.bind('add', this.startgame); games.bind('reset', this.getgame); games.fetch(); }, newgame: function(event) { games.create(); return false; }, getgame: function() { var existing = games.existing(); var unused = games.unused(); if(existing.length) this.startgame(existing[0]); else if(unused.length) this.startgame(unused[0]); else games.create(); }, startgame: function(game) { var view = new gameview({ model: game }); view.render(); } }); var app = new appview; });
there ever 1 instance of model. can have many views of same model. when 1 view expires, remove dom.
$(this.el).remove();
Comments
Post a Comment