backstopmedia / hubbub

Sample project for the book Developing a Backbone.js Edge
http://backstopmedia.github.com/hubbub/
21 stars 111 forks source link

app.ListView() #25

Closed caseywebdev closed 11 years ago

caseywebdev commented 11 years ago

I use this in a project I'm working on

(function () {
  'use strict';

  var $ = window.jQuery;
  var app = window.app;
  var Backbone = window.Backbone;

  app.ListView = Backbone.View.extend({
    initialize: function () {
      this.views = {};
      this.listenTo(this.collection, {
        add: this.addModel,
        sort: this.sortModels,
        remove: this.removeModel
      });
    },

    addModel: function (model) {
      this.$el.append((this.views[model.cid] = new this.options.ModelView({
        collection: this.collection,
        model: model
      })).el);
    },

    sortModels: function () {
      var views = this.views;
      var $el = this.$el;
      var $models = $el.children();
      this.collection.each(function (model, i) {
        var el = views[model.cid].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) {
      delete this.views[model.cid];
    }
  });
})();
afeld commented 11 years ago

Very cool. Nice example (besides the modal) of making a reusable component.

caseywebdev commented 11 years ago

Bringing it into the project :+1:

philfreo commented 11 years ago

@caseywebdev remove needs to remove / clean up all the subview right?

caseywebdev commented 11 years ago

Yes, working on it.