backbone.projections
Version:
Various projections for Backbone.Collection
109 lines (93 loc) • 3.27 kB
JavaScript
// Generated by CoffeeScript 1.6.2
var Collection, extend, inducedOrdering, toArray, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Collection = ((typeof window !== "undefined" && window !== null ? window.Backbone : void 0) || require('backbone')).Collection;
_ref = (typeof window !== "undefined" && window !== null ? window._ : void 0) || require('underscore'), toArray = _ref.toArray, extend = _ref.extend;
inducedOrdering = function(collection) {
var func;
func = function(model) {
return collection.indexOf(model);
};
func.induced = true;
return func;
};
exports.Capped = (function(_super) {
__extends(Capped, _super);
function Capped(underlying, options) {
var _this = this;
if (options == null) {
options = {};
}
this.underlying = underlying;
this.model = underlying.model;
this.comparator = options.comparator || inducedOrdering(underlying);
this.options = extend({
cap: 5
}, underlying.options, options);
Capped.__super__.constructor.call(this, this._capped(this.underlying.models), options);
this.listenTo(this.underlying, {
reset: function() {
return _this.reset(_this._capped(_this.underlying.models));
},
remove: function(model) {
var capped;
if (_this.contains(model)) {
_this.remove(model);
capped = _this._capped(_this.underlying.models);
return _this.add(capped[_this.options.cap - 1]);
}
},
add: function(model) {
if (_this.length < _this.options.cap) {
return _this.add(model);
} else if (_this.comparator(model) < _this.comparator(_this.last())) {
_this.add(model);
return _this.remove(_this.at(_this.options.cap));
}
},
sort: function() {
if (_this.comparator.induced) {
return _this.reset(_this._capped(_this.underlying.models));
}
}
});
}
Capped.prototype._capped = function(models) {
var _this = this;
models = toArray(models);
models.sort(function(a, b) {
a = _this.comparator(a);
b = _this.comparator(b);
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
});
return models.slice(0, this.options.cap);
};
Capped.prototype.resize = function(cap) {
var capped, idx, model, _i, _ref1;
if (this.options.cap > cap) {
this.options.cap = cap;
_ref1 = this.models;
for (idx = _i = _ref1.length - 1; _i >= 0; idx = _i += -1) {
model = _ref1[idx];
if (idx < cap) {
break;
}
this.remove(model);
}
} else if (this.options.cap < cap) {
this.options.cap = cap;
capped = this._capped(this.underlying.models);
this.add(capped.slice(this.length, this.options.cap));
}
return this.trigger('resize');
};
return Capped;
})(Collection);
exports.CappedCollection = exports.Capped;