Created
April 2, 2014 00:04
-
-
Save dburles/9925532 to your computer and use it in GitHub Desktop.
Meetup
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
## Meteor Patterns ## | |
---------- | |
# 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) { | |
return Books.find({ | |
name: { $regex: RegExp.escape(query), $options: 'i' } | |
}); | |
}; | |
``` | |
---------- | |
### Publication | |
> server/publications.js | |
```js | |
Meteor.publish('booksSearch', function(query) { | |
if (_.isEmpty(query)) | |
return this.ready(); | |
return Books.search(query); | |
}); | |
``` | |
---------- | |
### Client Stuff | |
> client/views/books.html | |
```html | |
<template name="books"> | |
<input type="text"> | |
{{#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({ | |
'keydown input[type="text"]': function(event, template) { | |
Session.set('booksSearchQuery', event.target.value); | |
} | |
}); | |
Template.books.helpers({ | |
searchResults: function() { | |
return Books.search(Session.get('booksSearchQuery')); | |
} | |
}); | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment