javascript - Backbone.js: How to handle selection of a single view only? -
i stuck on following issue:
i have model property defines if visibly selected or not, call selectmodel purpose of question.
selectmodel = backbone.model.extend({ defaults:{ isselected: false } })
now first part not how should handle selection in general. if want use observer pattern, view should listen change of isselected property. view triggers in first place, have.
selectview = backbone.view.extend({ initialize: function(){ this.model.bind("change:isselected", this.toggleselectionvisually) }, events: { "click" : toggleselection }, toggleselection: function(){ this.model.set({"isselected": !this.model.get("isselected"); }, toggleselectionvisually:(){ //some code shows view selected }, })
so in feels bit absurd guess understand wrong.
but part fail implement without making code horrible handling selection multiple models 1 model selected @ time.
selectlistview = backbone.view.extend({ initialize: function(){ this.collection = new selectlist(); }, toggleselection: function(){ ???? } })
so should notify whom of selection change? part should trigger , part should listen? stuck on one. single view doable, collection sadly lost.
i have suggested following simplification selectview
until saw second part of question:
selectview = backbone.view.extend({ events: { "click" : toggleselection }, toggleselection: function(){ this.model.set({"isselected": !this.model.get("isselected"); //some code shows whether view selected or not } });
however, since isselected
attribute apparently mutually exclusive, can toggled off implicitly when 1 toggled on, think way have best case.
so, using existing selectview
and, have selectlistview
follows. warning: iterates on entire collection of models each time 1 selected. if have large number of models not scale well, , you'll want cache previously-selected model rather iterating on entire collection.
selectlistview = backbone.view.extend({ initialize: function(){ this.collection = new selectlist(); this.collection.bind('change:isselected', this.toggleselection, this); }, toggleselection: function(toggledmodel){ //a model toggled (on or off) if(toggledmodel.get('isselected') { //a model toggled on, check if different model selected var otherselectedmodel = this.collection.find(function(model) { return toggledmodel !== model && model.get('isselected'); }); if(otherselectedmodel != null) { //another model selected, toggle off otherselectedmodel.set({'isselected': false}); } } } });
Comments
Post a Comment