Skip to content

Instantly share code, notes, and snippets.

@nummi
Last active August 29, 2015 14:14
Show Gist options
  • Save nummi/25f1dc52564e2f767275 to your computer and use it in GitHub Desktop.
Save nummi/25f1dc52564e2f767275 to your computer and use it in GitHub Desktop.
Ember Flash Messages, Component, Service and Initializer
// app/pods/components/flash-message/component.js
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['flash-message'],
classNameBindings: ['type'],
layoutName: 'flash-message',
type: function() {
return 'flash-message--' + this.get('message.type');
}.property('message.type'),
fadeIn: function() {
this.$().hide().fadeIn(250);
}.on('didInsertElement'),
actions: {
remove: function() {
var self = this;
this.$().fadeOut(function() {
self.sendAction('remove', this.get('message'));
});
}
}
});
{{! app/pods/components/flash-message/template.hbs }}
<div class="flash-message-content">
{{message.text}}
<div class="flash-message-remove" {{action "remove"}}>&times;</div>
</div>
// app/pods/components/flash-messages/component.js
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['flash-messages'],
layoutName: 'flash-messages',
actions: {
removeMessage: function(message) {
this.get('flash.messages').removeObject(message);
}
}
});
{{! app/pods/components/flash-messages/template.hbs }}
{{#each message in flash.messages}}
<flash-message remove={{action "removeMessage"}} message={{message}}</flash-message>
{{/each}}
// app/initializers/flash-messages.js
import Flash from 'tahi/services/flash';
export default {
name: 'flashMessages',
initialize: function(container, application) {
container.register('flashMessages:main', Flash);
application.inject('route', 'flash', 'flashMessages:main');
application.inject('controller', 'flash', 'flashMessages:main');
application.inject('component:flashMessages', 'flash', 'flashMessages:main');
Ember.Route.reopen({
_teardownFlashMessages: function() {
this.flash.clearMessages();
}.on('deactivate')
});
}
};
// app/services/flash.js
import Ember from 'ember';
export default Ember.Object.extend({
messages: [],
displayMessage: function(type, message) {
this.get('messages').pushObject({
text: message,
type: type
});
},
displayErrorMessagesFromResponse: function(response) {
for (var key in response.errors) {
if(!response.errors.hasOwnProperty(key)) { continue; }
this.displayMessage('error', this.formatKey(key) + ' ' + response.errors[key].join(', '));
}
},
formatKey: function(key) {
return key.underscore().replace('_', ' ').capitalize();
},
clearMessages: function() {
this.set('messages', []);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment