Skip to content

Instantly share code, notes, and snippets.

@dburles
Last active August 29, 2015 13:56
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/8857046 to your computer and use it in GitHub Desktop.
Save dburles/8857046 to your computer and use it in GitHub Desktop.
# Making everything reactive!
#### The goal: Display the 10 latest `Books` along with their respective `Authors`
# Example 1.
> Authors are *not* reactive
> The problem with this approach is that once a new book (with a new author) appears,
> the new author is not sent to the client
```javascript
Meteor.publish('booksWithAuthors', function() {
var books = Books.find({}, { sort: { createdAt: -1 }, limit: 10 });
return [
books,
Authors.find({ _id: { $in: _.uniq(books.map(function(book) { return book.authorId; })) }})
];
});
```
> Subscribe:
```javascript
Meteor.subscribe('booksWithAuthors');
```
# Example 2.
> Authors are reactive
> This is basically what reactive-relations automates
```javascript
Meteor.publish('booksWithAuthors', function(authorIds) {
var books = Books.find({}, { sort: { createdAt: -1 }, limit: 10 });
> Send through the authors initally
if (authorIds.length === 0)
authorIds = books.map(function(book) { return book.authorId; });
return [
books,
Authors.find({ _id: { $in: _.uniq(authorIds) }})
];
});
```
> Subscribe on the client, passing through an array containing the authorIds that we require
```javascript
Deps.autorun(function() {
```
> Books query ends up being duplicated here!
```javascript
var books = Books.find({}, { sort: { createdAt: -1 }, limit: 10 });
```
> As does this mapping function
```javascript
Meteor.subscribe('booksWithAuthors', books.map(function(book) { return book.authorId; }));
});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment