/src/views/listview.js
JavaScript | 80 lines | 46 code | 13 blank | 21 comment | 4 complexity | 6e74807fc418187fe42ccf314eaaf33d MD5 | raw file
- define([
- 'underscore',
- 'backbone',
- 'views/singleview'
- ], function (
- util,
- Backbone,
- SingleView
- ) {
- var slice = Array.prototype.slice;
- // An ordered set of sub-views.
- // Conceptually corresponds to an array.
- // Usage:
- //
- // var view = new ListView({
- // view: MyViewCtor
- // });
- // view.collection.add(new Backbone.Model());
- var ListView = Backbone.View.extend({
- initialize: function (options) {
- options = options || {};
- this.collection = options.collection || new Backbone.Collection();
- // Set target element for subviews. Use scoped selector if element
- // isn't `this.el`.
- this.target = options.target ? this.$(options.target) : this.el;
-
- // Set subview constructor.
- this.view = options.view || SingleView;
-
- if (options.bridge) this.bridge = options.bridge;
-
- this.collection
- .bind('add', this.addView, this)
- .bind('reset', this.resetViews, this);
-
- this.resetViews(this.collection);
- },
-
- // General factory for subviews.
- createView: function () {
- // Create an options object by getting all of the objects passed in.
- // This allows for multiple options objects to be curried onto the
- // function -- useful for specializing the way subviews are created.
- var options = util.extend.apply(this, arguments),
- // Pick a view.
- View = this.filterView.call(options, this.view),
- view = new View(options);
-
- // Fire an event, allow others to modify view.
- this.trigger('add', this, view);
-
- // Append a view to the DOM. It needs to know how to add and remove
- // itself.
- $(this.target).append(view.render().el);
- return this;
- },
-
- filterView: function (View) {
- return View;
- },
-
- // Specialized factory for use with binding to model events.
- addView: function (model) {
- this.createView({ model: model, bridge: this.bridge });
- },
-
- // Specialized factory for use with binding to collection events.
- resetViews: function (collection) {
- $(this.target).html('');
- collection.each(this.addView, this);
- },
- render: function () {
- return this;
- }
- });
-
- return ListView;
- });