Flash Your Local Collection

Rails allows you to pass messages to the user between actions (“This ActionDispatch::Flash will self-destruct”), and because Rails, all the message generation happens server side:

flashy_controller.rb
1
2
3
def show
  flash[:notice] = "You dropped your packet."
end

Meteor is mostly a client-side application framework, and you can implement a similar message system, which will never touch the server, by defining a collection that is local to the browser.

1. Create a local collection

/client/errors.js
1
Errors = new Meteor.Collection(null);

Passing null into the Collection declaration tells Meteor that the collection should not be extended to the server — it creates an “unmanaged (unsynchronized) local collection” (docs)

2. Throw an error whenever you need to

/missionCritical.js
1
2
3
if(error){
  Errors.insert({message: error.reason});
}

3. Create a template for displaying the error

/client/errors.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template name="errors">
  <div class="errors">
    {{#each errors}}
      {{> error}}
    {{/each}}
  </div>
</template>

<template name="error">
  <div class="alert alert-error">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{message}}
  </div>
</template>

4. Create a helper method for serving the errors to the template

/client/errors.js continued again
1
2
3
4
5
...
Template.errors.helpers({
  errors: function() {
    return Errors.find();
  }

Every template that contains the handlebars {{> errors}} will now display whatever errors have been saved to the session collection.

Awesome.

Resources

discovermeteor.com Meteor docs