Created
October 4, 2012 15:08
-
-
Save matb33/3834232 to your computer and use it in GitHub Desktop.
Alternate _publishCursor for Meteor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Meteor extension to allow modifications to documents when publishing. | |
// Also allows specifying an alternate name under which to publish the | |
// collection, using "sub_name". | |
_.extend(Meteor._LivedataSubscription.prototype, { | |
_publishCursor: function (cursor, name) { | |
var self = this; | |
var collection = name || cursor.sub_name || cursor.collection_name; | |
var map_callback = cursor.map_callback || function (obj) { return obj; }; | |
var observe_handle = cursor.observe({ | |
added: function (obj) { | |
var mod_obj = map_callback.call(self, obj); | |
if (mod_obj === false) { | |
self.unset(collection, obj._id, _.keys(obj)); | |
} else { | |
self.set(collection, mod_obj._id, mod_obj); | |
} | |
self.flush(); | |
}, | |
changed: function (obj, old_idx, old_obj) { | |
var set = {}, mod_obj = map_callback.call(self, obj); | |
if (mod_obj === false) { | |
self.unset(collection, obj._id, _.keys(obj)); | |
} else { | |
_.each(mod_obj, function (v, k) { | |
if (!_.isEqual(v, old_obj[k])) { | |
set[k] = v; | |
} | |
}); | |
self.set(collection, mod_obj._id, set); | |
var dead_keys = _.difference(_.keys(old_obj), _.keys(mod_obj)); | |
self.unset(collection, mod_obj._id, dead_keys); | |
} | |
self.flush(); | |
}, | |
removed: function (old_obj, old_idx) { | |
var mod_old_obj = map_callback.call(self, old_obj); | |
if (mod_old_obj !== false) { | |
self.unset(collection, mod_old_obj._id, _.keys(mod_old_obj)); | |
self.flush(); | |
} | |
} | |
}); | |
self.complete(); | |
self.flush(); | |
self.onStop(_.bind(observe_handle.stop, observe_handle)); | |
} | |
}); |
@matb33 ... I am having to publish a modified cursor. Any suggested way you have identified to do this?
This is very helpful when you may have data collision or you want to track the data subscription origin in a components model.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't use this =) Meteor has come a long way since, and so has my understanding of how Meteor works. If you find yourself needing this code, you may be doing something wrong.