Aaron Van Bokhoven

Ember.js Flash Messages

Written by Aaron Van Bokhoven on June 18, 2013

This is a simple way to create flash messages that are similar to the Ruby on Rails flash messages. I took from Yehuda Katz’s answer on this Stack Overflow post, and extended it to work with the updated controllerFor/needs changes and closing on transitions.

In the application.handlebars template I create a condition that checks if the notification variable is set, and if it is, display it with it’s message and alert-type class(error, success, info, etc).

In the application controller, there’s a function that creates the notification and passes options to it, and there’s also a function that closes the notification. The closeNotification first checks for a ‘persists’ flag and if it doesn’t exist it sets the notification variable to null, which closes it. If a ‘persists’ flag does exist, it sets it the flag to null and skips closing the notification. On the next transition, the ‘persists’ flag wont exist and the notification will be closed.

In the posts new controller, at the top I have a needs array, which let’s the controller know that we need access to the application controller. The notifications are hooked into the ‘on’ callbacks for the post model, and called by using @get(‘controllers.application’).notify(). In earlier versions of Ember.js you would directly use the controllerFor() function, but that was deprecated for ‘needs’.

Lastly in the router, I created an App.BeforeRoute extension of Ember.Route which all of my routes extend from. This way every route will execute the activate function, which executes the closeNotification function, before every route loads.