Last active
August 29, 2015 13:56
-
-
Save dburles/8857046 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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