Skip to content

Instantly share code, notes, and snippets.

@dburles
Created April 2, 2014 11:58
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/9932699 to your computer and use it in GitHub Desktop.
Save dburles/9932699 to your computer and use it in GitHub Desktop.
Meetup
## Meteor Patterns ##
----------
# 1. Simple Search
- Avoid duplicating the same query code on the client and server.
- Provide some simple search results.
> common/utils.js
```js
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
```
----------
### Common Cursor:
> common/collections/books.js
```js
Books = new Meteor.Collection('books');
Books.search = function(query) {
if (_.isEmpty(query))
return;
return Books.find({
name: { $regex: RegExp.escape(query), $options: 'i' }
});
};
```
----------
### Publication
> server/publications.js
```js
Meteor.publish('booksSearch', function(query) {
check(query, String);
if (_.isEmpty(query))
return this.ready();
return Books.search(query);
});
```
----------
### Client Stuff
> client/views/books.html
```html
<template name="books">
<input type="text" placeholder="Search..." value="{{booksSearchQuery}}">
{{#if searchResults.count}}
<ul>
{{#each searchResults}}
<li>{{name}}</li>
{{/each}}
</ul>
{{/if}}
</template>
```
> client/views/books.js
```js
Deps.autorun(function() {
Meteor.subscribe('booksSearch', Session.get('booksSearchQuery'));
});
Template.books.events({
'keyup [type="text"]': function(event, template) {
Session.set('booksSearchQuery', event.target.value);
}
});
Template.books.helpers({
searchResults: function() {
return Books.search(Session.get('booksSearchQuery'));
},
booksSearchQuery: function() {
return Session.get('booksSearchQuery');
}
});
```
----------
# 2. Publications for signed-in users
### Regular way
```js
Meteor.publish('books', function() {
if (! this.userId)
return this.ready();
return Books.find({ userId: this.userId });
});
Meteor.publish('authors', function() {
if (! this.userId)
return this.ready();
return Authors.find({ userId: this.userId });
});
```
### With wrapper function
```js
Meteor.publishAuth = function(name, fn) {
Meteor.publish(name, function() {
if (! this.userId)
return this.ready();
return fn.apply(this, arguments);
});
};
Meteor.publishAuth('books', function() {
return Books.find({ userId: this.userId });
});
Meteor.publishAuth('authors', function() {
return Authors.find({ userId: this.userId });
});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment