'li'; super(); } initialize(options) { _.bindAll(this, 'render', 'remove'); this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); } render() { $(this.el).html(_.template('<span><%- b %></span>', this.model.toJSON())); return this; } } class InputView extends RawView { render() { $(this.el).html(_.template('<input val="<%- b %>">', this.model.toJSON())); return this; } } class EscapeView extends RawView { render() { $(this.el).html(_.template('<span><%- _.escape(b) %></span>">', this.model.toJSON())); return this; } } { items: [{t: 'text', b:'foo'}] } <ul id='items'> <li>foo</li> </ul> { items: [
{t: 'text', b: 'foo'},
{t: 'edit', b: '<i>bar</i>'}
] } <ul id='items'> <li>foo</li> <li><input value='<i>bar</i>'></li> </ul> class CollectionView extends Backbone.View { constructor() { this.el = '#items'; super(); } initialize(options) { _.bindAll(this, 'resetItems', 'appendItem', 'removeItem'); this.listenTo(this.collection, 'reset', this.resetItems); this.listenTo(this.collection, 'add', this.appendItem); this.listenTo(this.collection, 'remove', this.removeItem); } resetItems(collection) { collection.each((model) => this.appendItem(model)); } appendItem(model) { var view; switch (model.get('t')) { case 'text': view = new EscapeView({model}); break; case 'tmpl': view = new RawView({model}); break; case 'edit': view = new InputView({model}); break; } var view = new ModelView({model}); $(this.el).append(view.render().el); } removeItem(model) { model.destroy(); } } var collection = new Backbone.Collection(items); new CollectionView({collection}); ͳɹ͕ɹ͍ ͜ͷྫͩͱModel୯ಠ͕ͩ
Model͕ෳʹͳΔͱ
͞Βʹάονϟάνϟʹͳ͍ͬͯ͘ http://goo.gl/aiVQks