diff --git a/index.html b/index.html index ec560df..737bc8b 100644 --- a/index.html +++ b/index.html @@ -19,6 +19,7 @@ + diff --git a/views/list.js b/views/list.js new file mode 100644 index 0000000..5c705eb --- /dev/null +++ b/views/list.js @@ -0,0 +1,48 @@ +(function () { + 'use strict'; + + var $ = window.jQuery; + var _ = window._; + var app = window.app; + + app.ListView = Backbone.View.extend({ + initialize: function () { + this.views = {}; + this.listenTo(this.collection, { + add: this.addModel, + sort: this.sortModels, + remove: this.removeModel + }); + this.collection.each(this.addModel, this); + }, + + addModel: function (model) { + this.$el.append((this.views[model.cid] = new this.options.modelView({ + collection: this.collection, + model: model + })).render().el); + }, + + sortModels: function () { + var views = this.views; + var $el = this.$el; + var $models = $el.children(); + this.collection.each(function (model, i) { + var view = views[model.cid]; + if (!view) return; + var el = view.el; + if (!$models[i]) { + $el.append(el); + } else if ($models[i] !== el) { + $models.eq(i).before(el); + $models = $($models.get().splice(i, 0, el)); + } + }); + }, + + removeModel: function (model) { + this.views[model.cid].remove(); + delete this.views[model.cid]; + } + }); +})();