Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Backbone.MeteorCollection, a subclass of Backbone.Collection that updates from a Meteor collection using More info and examples at
Backbone.MeteorCollection = Backbone.Collection.extend({
_reactiveQuery: null,
_waitOn: null,
* @param {object} options
* @property {ReactiveQuery} reactiveQuery - The query to observe.
* @property {Subscription=} waitOn - (Optional) A subscription whose record set corresponds to
* _reactiveQuery_. If specified, the collection will wait until the subscription becomes ready
* before beginning to observe the query. This avoids emitting 'add' events for every record
* in the initial set; rather, the collection will reset itself to the query's result set
* (and emit a single 'reset' event) when the subscription becomes ready.
initialize: function(models, options) {
if (!(this.model.prototype instanceof Backbone.MeteorModel)) {
throw 'MeteorCollection models must derive from MeteorModel for syncing to work right.';
this._reactiveQuery = options.reactiveQuery;
this._waitOn = options.waitOn;
if (this._waitOn) {
this._waitOn.whenReady().then(function() {
// Once the relevant subscription is ready, reset the collection to the current state of the
// result set. (We've skipped over the initial 'add' events.)
} else {
_beginObservingChanges: function() {
.on('added', function(id, fields) {
var doc = _.extend({ _id: id }, fields);
// If the collection was not instructed to wait for the relevant subscription to become ready,
// this will be called for the initial result set. Since that may overlap with the models
// with which the collection was initialized, we merge the models.
this.add(doc, { merge: true });
}, this)
.on('changed', function(id, fields) {
var model = this.get(id);
if (model) {
var toUnset = _.pick(fields, _.isUndefined);
var toSet = _.omit(fields, _.isUndefined);
}, this)
.on('removed', function(id) {
var model = this.get(id);
if (model) {
}, this);
Backbone.MeteorModel = Backbone.Model.extend({
idAttribute: '_id'
Copy link

wearhere commented May 22, 2015

This will be renamed/polished/packaged as a full-fledge open-source project soon. In the meantime, this requires:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment