Skip to content

Instantly share code, notes, and snippets.

@max-power
Last active December 9, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-power/4334784 to your computer and use it in GitHub Desktop.
Save max-power/4334784 to your computer and use it in GitHub Desktop.
Backbone.js Collection Views: - UnorderedList - OrderedList - Table
var listViewsRoot = window
;(function(ns){
// LIST ITEMS
ns.ListItem = Backbone.View.extend({
tagName: 'li',
template: '<%= id %>',
render: function(){
var tmpl = _.template(this.options.template || this.template)
this.$el.html(tmpl(this.renderContext()))
return this
},
renderContext: function(){
return this.model.toJSON()
}
})
ns.TableRow = ns.ListItem.extend({ tagName: 'tr', template: '<td><%= id %></td>' })
// LISTS
ns.List = Backbone.View.extend({
tagName: 'ul',
itemView: ns.ListItem,
constructor: function(options){
Backbone.View.prototype.constructor.apply(this, arguments)
this.subViews = {}
if (options.itemTemplate) this.itemTemplate = options.itemTemplate
if (options.itemView) this.itemView = options.itemView
this.listenTo(this.collection, 'add', this.appendView)
this.listenTo(this.collection, 'remove', this.removeView)
this.listenTo(this.collection, 'reset sort', this.render)
},
render: function(){
this.removeAllViews().collection.each(this.appendView, this)
return this
},
appendView: function(model){
var view = new this.itemView({ model: model, template: this.itemTemplate })
this.subViews[model.cid] = view
this.$el.append(view.render().el)
return this.trigger('subview:added', view)
},
removeView: function(model) {
var view = this.subViews[model.cid]
if (view) {
view.remove()
delete this.subViews[model.cid]
this.trigger('subview:removed', view)
}
return this
},
removeAllViews: function() {
_.invoke(this.subViews, 'remove')
this.subViews = {}
return this
}
})
ns.UnorderedList = ns.List
ns.OrderedList = ns.List.extend({ tagName: 'ol' })
ns.Table = ns.List.extend({ tagName: 'table', itemView: ns.TableRow })
})(listViewsRoot)
var collection = new Backbone.Collection() // some Collection
var list = new List({collection: collection})
var ordered = new OrderedList({collection: collection})
var table = new Table({collection: collection})
// set the itemTemplate
new List({collection: collection, itemTemplate: '<b><%= name %></b>'})
// set a itemView
var myListItemView = ListItem.extend({
template: '<b><%= name %></b>',
events: {'click': 'render'}
})
new List({collection: collection, itemView: myListItemView })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment