Skip to content

Instantly share code, notes, and snippets.

@dburles
Created March 2, 2014 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dburles/9302416 to your computer and use it in GitHub Desktop.
Save dburles/9302416 to your computer and use it in GitHub Desktop.
pub/sub pattern
//
// publish list of books (and authors)
//
Books.mainListCursor = function() {
return Books.find({}, { sort: { createdAt: -1 }, limit: 10 });
};
if (Meteor.isServer) {
Meteor.publish('books', function() {
var books = Books.mainListCursor();
return [
books,
Authors.find({ _id: { $in: books.map(function(book) { return book.authorId; }) }})
];
});
Meteor.publish('author', function(_id) {
return Authors.find(_id);
});
}
if (Meteor.isClient) {
Meteor.subscribe('books');
Deps.autorun(function() {
Books.mainListCursor().forEach(function(book) {
Meteor.subscribe('author', book.authorId);
});
});
}
//
// publish list of 5 authors and all of their books
//
Authors.mainListCursor = function() {
return Authors.find({}, { sort: { createdAt: -1 }, limit: 5 });
};
if (Meteor.isServer) {
Meteor.publish('authors', function() {
var authors = Authors.mainListCursor();
return [
authors,
Books.find({ authorId: { $in: authors.map(function(author) { return author._id; }) }})
];
});
Meteor.publish('bookByAuthorId', function(authorId) {
return Books.find({ authorId: authorId });
});
}
if (Meteor.isClient) {
Meteor.subscribe('authors');
Deps.autorun(function() {
Authors.mainListCursor().forEach(function(author) {
Meteor.subscribe('bookByAuthorId', author._id);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment