Skip to content

Instantly share code, notes, and snippets.

@imlucas
Last active October 20, 2015 21:38
Show Gist options
  • Save imlucas/283d9acc3a3c84cae319 to your computer and use it in GitHub Desktop.
Save imlucas/283d9acc3a3c84cae319 to your computer and use it in GitHub Desktop.
piping ampersand.js collections
var View = require('ampersand-view');
var Base = require('../models/connection-collection');
var debug = require('debug')('connect:multi-collection-example');
var ConnectionCollection = Base.extend({
initialize: function(models, options){
options = options || {};
Base.prototype.initialize.call(this, models, options);
},
pipe: function(dest){
dest.listenTo(this, 'add', function(model, collection, opts){
debug('Model added! Applying to dest', {
model: model,
collection: collection,
options: opts
});
dest.add(model, opts);
});
dest.listenTo(this, 'remove', function(model, collection, opts){
debug('Model removed! Applying to dest', {
model: model,
collection: collection,
options: opts
});
dest.remove(model, opts);
});
dest.listenTo(this, 'sort', dest.sort.bind(dest));
dest.listenTo(this, 'reset', dest.reset.bind(dest));
return this;
}
});
var ConnectionHistoryCollection = ConnectionCollection.extend({
// Instead of applying separate sorts,
// just extend the base collection
// w/ a custom comparator.
comparator: 'created_on'
});
View.extend({
collections: {
// Submiting form/destroying still adds to this
// to this master collection.
connections: ConnectionCollection,
// Filtered replication from `this.connections` :p
favorites: ConnectionCollection,
// Replicated map reduce result from `this.connections` :p
history: ConnectionHistoryCollection
},
initialize: function(){
this.favorites.filter(function(c){
return c.is_favorite === true;
});
this.history.filter(function(c){
// if you want to make favorites and history
// mutally exclusive
return c.is_favorite === false;
});
// Connect main `this.connections` collection
// so operations applied to it are also applied
// to `this.history` and `this.history`.
// filter and comparator will automatically
// so the right thing (I Hope).
this.connections
.pipe(this.favorites)
.pipe(this.history)
.fetch();
},
template: '<div>'
+ '<div data-hook="favorite-connection-list"></div>'
+ '<div data-hook="recent-connection-list"></div>'
+'</div>',
render: function(){
this.renderWithTemplate();
this.renderCollection(this.favorites,
ConnectionListItemView,
'favorite-connection-list');
this.renderCollection(this.history,
ConnectionListItemView,
'recent-connection-list');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment