Last active
August 29, 2015 14:04
-
-
Save Carolusian/6ee0129e0ac22eb4635a to your computer and use it in GitHub Desktop.
Backbone.js Notifications: The Quick and Easy Way
This file contains 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
window.NotificationView = Backbone.View.extend({ | |
targetElement:'#message' | |
tagName: 'div' | |
className: 'notification' | |
defaultMessages: | |
'success': 'Success!' | |
'error': 'Sorry! An error occurred in the process' | |
'warning': 'Are you sure you want to take this action?' | |
'information': 'An unknown event occurred' | |
cssClasses: | |
'success':'accepted' | |
'error':'cancel' | |
'warning': 'warning' | |
'information': 'information' | |
events: | |
'click': 'closeNotification' | |
automaticClose: true | |
initialize: (options) -> | |
type = 'information' | |
target = @targetElement | |
if options and options.hasOwnProperty('type') | |
type = options.type | |
text = @defaultMessages[type] | |
if options and options.hasOwnProperty('text') | |
text = options.text | |
if options and options.hasOwnProperty('target') | |
target = options.target | |
console.log(text) | |
if options and options.hasOwnProperty('automaticClose') | |
@automaticClose = options.automaticClose | |
if ($ '.notification:contains("+text+")').length == 0 | |
@render(type, text, target) | |
render: (type, text, target) -> | |
self = @ | |
# Clear all previous messages | |
self.closeNotification() | |
this.$el.addClass(@cssClasses[type]) | |
loopErrors = (v, k) -> | |
# This part is particular for django forms, it will append | |
# a div to the end of relevant field | |
($ "[name="+k+"]").after("<div class='notification'>"+v+"</div>") | |
# If the error message is a object instance | |
# If will loop thought the k, v of each property | |
# and call loopErrors | |
if(_.isObject(text)) | |
_.each(text, loopErrors) | |
else | |
# If the error message is nothing more than string, just | |
# prepend it to the target elem | |
this.$el.text(text) | |
this.$el.prependTo(this.targetElement) | |
if @automaticClose | |
setTimeout(( | |
-> self.closeNotification()), 5000) | |
closeNotification: () -> | |
self = @ | |
$(".notification").fadeOut ()-> | |
self.unbind() | |
self.remove() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment