collection.js | |
---|---|
Collection ViewManages rendering many views with a collection See: http://liquidmedia.ca/blog/2011/02/lib-js-part-3/ | |
The CollectionView extends BaseView and is intended for rendering a collection. A item view is required for rendering withing each iteration over the models. | |
Requires | define(['facade','views/base','utils'], function (facade, BaseView, utils) {
var CollectionView,
$ = facade.$,
_ = facade._,
Backbone = facade.Backbone,
debug = utils.debug; |
Constructor | CollectionView = BaseView.extend({ |
Method: | initialize : function (options) {
var collection, msg;
if (!this.collection || !(this.collection instanceof Backbone.Collection)) {
msg = "CollectionView initialize: no collection provided.";
throw new Error(msg);
}
BaseView.prototype.initialize.call(this, options);
this._view = this.options.view || this._view;
if (!this._view) {
throw new Error("CollectionView initialize: no view provided.");
}
this._tagName = this.options.tagName || this._tagName;
if (!this._tagName) {
throw new Error("CollectionView initialize: no tag name provided.");
}
this._className = this.options.className;
this._decorator = this.options.decorator;
this._id = this.options.id;
this._views = [];
_(this).bindAll('add', 'remove');
this.setupCollection();
}, |
Method: | setupCollection: function () {
var collection = this.options.collection || this.collection;
collection.on('add', this.add);
collection.on('remove', this.remove);
if (!collection.length && !collection.request) {
collection.request = collection.fetch();
collection.request.done(function () {
collection.each(collection.add);
});
} else {
collection.each(this.add);
}
}, |
Method: | add : function(model) {
var view;
view = new this._view({
"tagName": this._tagName,
"model": model,
"className": this._className,
"decorator": this._decorator
});
this._views.push(view);
if (this._rendered) {
this.$el.append(view.render().el);
}
}, |
Method: | remove : function(model) {
var viewToRemove;
viewToRemove = _(this._views).select(function(cv) {
return cv.model === model;
})[0];
this._views = _(this._views).without(viewToRemove);
if (this._rendered) {
viewToRemove.destroy(); // $(viewToRemove.el).off().remove();
}
}, |
Method: | render : function() {
this.confirmElement.call(this);
this._rendered = true;
this.$el.empty();
_(this._views).each(function(view) {
this.$el.append(view.render().el);
if (view.options.decorator && _.isFunction(view.options.decorator)) {
view.options.decorator(view);
}
}, this);
this.resolve.call(this);
this.callbacks.fire.call(this);
return this;
}
});
return CollectionView;
});
|