Skip to content

Instantly share code, notes, and snippets.

@jonjamz
Last active January 26, 2017 10:50
Show Gist options
  • Save jonjamz/bbd1c65b0f7cdd7ca461 to your computer and use it in GitHub Desktop.
Save jonjamz/bbd1c65b0f7cdd7ca461 to your computer and use it in GitHub Desktop.
Alternative to Meteor.Collection._publishCursor that returns the observeChanges handle
###
When attempting to use Meteor.Collection._publishCursor in publish functions as part of a join,
we'll do something like this (as outlined in Discover Meteor's Advanced Publications chapter):
Meteor.publish (authorId) ->
sub = @
commentHandles = {}
unless @userId?
return undefined
publishPostComments = (postId) ->
# A handle for these comments
commentsCursor = Comments.find
postId: postId
,
sort: createdAt: -1
commentHandles[postId] = Meteor.Collection._publishCursor(commentsCursor, sub, "comments")
postsHandle = Posts.find({author: @userId}).observeChanges
added: (id, fields) ->
# When a new post is added, publish the related comments
publishPostComments id
removed: (id) ->
# Stop publishing the comments for the removed post
commentHandles[id] and commentHandles[id].stop()
The problem is, Meteor.Collection._publishCursor has no stop method!
We need to have access to the observeChanges handle from _publishCursor
so we can stop unnecessary cursor publishing. As it stands, this handle
is not returned. Instead, it only stops the cursor using the publish
function's onStop method, when the entire publish function is stopped.
So I wrote an alternative method for _publishCursor that gives us the
handle we need. Here it is...
Just add this so it loads before your publish functions and change
_publishCursor to autoPublishCursor in your publications.
###
Meteor.Collection.autoPublishCursor = (cursor, sub, collection) ->
observeHandle = cursor.observeChanges
added: (id, fields) ->
sub.added collection, id, fields
changed: (id, fields) ->
sub.changed collection, id, fields
removed: (id) ->
sub.removed collection, id
sub.onStop ->
observeHandle.stop()
return observeHandle
@jonjamz
Copy link
Author

jonjamz commented Jan 26, 2017

Note: Meteor.Collection._publishCursor now does return the handle. So this isn't necessary.

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