Backbone - Example of single select from collection
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<h1>Veggie List</h1>
<ul id="veggieList"></ul>
CSS
h1 {
margin-top: 0;
}
ul li {
padding: 5px;
cursor: pointer;
}
ul li.selected {
background-color: #ccc;
}
JavaScript
/* MODELS */
var Item = Backbone.Model.extend();
var ItemList = Backbone.Collection.extend({
model: Item
});
/* VIEWS */
var ItemView = Backbone.View.extend({
tagName: "li"
, events: {
"click": "selectItem"
}
, initialize: function (){
this.model.bind("change:selected", this.onSelected, this);
}
, render: function () {
$(this.el).html(this.model.get("id"));
return this;
}
, selectItem: function (e){
var self = this, value = !this.model.get("selected");
// update the selected model's value
this.model.set({selected: value});
// if model was selected to false, stop processing
if( value === false ) return;
// loop through each model in the collection
this.collection.each(function (model){
// update any model that's not the currently click one
if( model.id !== self.model.id ){
model.set({selected: false});
}
});
}
, onSelected: function (model, value, options){
$(this.el)[value ? "addClass" : "removeClass"]("selected");
}
});
var ItemListView = Backbone.View.extend({
initialize: function(){
this.render();
}
, render: function(){
var self = this;
// clear out the existing list to avoid "append" duplication
$(this.el).empty();
// use an array here rather than firehosing the DOM perf is a bit better
var els = [];
// loop the collection...
this.collection.each(function(model){
// rendering a view for each model in the collection
var view = new ItemView({model: model, collection: self.collection});
// adding it to our array
els.push(view.render().el);
});
// push that array into this View's "el"
$(this.el).append(els);
return this;
}
});
var veggieList =...