flash your local collection

May 26, 2014

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:

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

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

if(error){
  Errors.insert({message: error.reason});
}

3. Create a template for displaying the error

<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

...
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


Mostly Katie explaining things to herself.

© 2022