0:61173cbe6827
Anton Shestakov <engored@ya.ru>, Wed, 05 Dec 2012 00:36:27 +0900
Made public.

next change 1:953d380d3035

backbone.shard.js

Permissions: -rw-r--r--

Other formats: Feeds:
/*
* backbone.shard.js.
*
* (c) 2012 Anton Shestakov.
*
* This extension to Backbone may be freely distributed
* under the MIT license:
* http://opensource.org/licenses/mit-license.php
*/
Backbone.Shard = function(options) {
this._collection = options.collection;
this._filter = options.filter;
this.models = this._collection.filter(this._filter);
this._collection
.on('all', function(event, model) {
if (/^change/.test(event) && this._filter(model) && this.models.indexOf(model) != -1) {
this.trigger.apply(this, arguments);
}
}, this)
.on('add', function(model) {
if (this._filter(model) && this.models.indexOf(model) == -1) {
this.models.push(model);
this.trigger('add', model);
}
}, this)
.on('remove', function(model) {
if (this._filter(model) && this.models.indexOf(model) != -1) {
this.models = _.without(this.models, model);
this.trigger('remove', model);
}
}, this)
.on('reset', function() {
this.models = this._collection.filter(this._filter);
this.trigger('reset');
}, this);
this.initialize.apply(this, arguments);
};
_.extend(Backbone.Shard.prototype, Backbone.Events, {
initialize: function() {}
});
// Underscore methods that we want to implement on the Shard.
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
// Mix in each Underscore method as a proxy to `Shard#models`.
_.each(methods, function(method) {
Backbone.Shard.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});