Backbone.js Notifications: The Quick and Easy Way

One of the more important components of a client-side application is a notification system that informs the user when certain events occur. Alerts such as “Item saved successfully” or “There was an error retrieving the data” are common messages that you might see in an application. Informing your users about certain events are an essential component of application development but how would you go about implementing this in a Backbone.js application?

Certainly you could opt for something sophisticated by importing a library that is specifically designed to handle notifications. But if you want a quick and easy way to implement notifications, probably the easiest thing to do is to just use create a Backbone View and instantiate it in your event handlers and call backs (i.e. the functions that run when certain events occur). In what follows we’ll look at a simple implementation that is flexible enough to handle a lot of the needs that a developer might have in implementing a notification system in his or her application. It probably won’t be a silver bullet fix-all that will be sufficient for every area of every application, but I believe it is structured in such a way that things could be extended to be a decent enough solution for a number of different instances.

So let’s look a the code below (discussion to follow)…

var 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: function(options){
        // defaults
        var type = 'information';
        var text = this.defaultMessages[type]; 
        var target = this.targetElement; 
        // if any options were set, override defaults
        if(options && options.hasOwnProperty('type'))
            type = options.type;
        if(options && options.hasOwnProperty('text'))
            text = options.text; 
        if(options && options.hasOwnProperty('target')) 
            target = options.target;
        if(options && options.hasOwnProperty('automaticClose'))
	    this.automaticClose = options.automaticClose;
        // is message already displayed in view? if yes, don't show again
        if($('.notification:contains('+text+')').length === 0) { 
            this.render(type, text, target);
        }
    },
    render: function(type, text, target){
        var self = this;
        this.$el.addClass(this.cssClasses[type]);
        this.$el.text(text);
        this.$el.prependTo(this.targetElement);
        // Automatically close after set time. also closes on click
        if(this.automaticClose) {
            setTimeout(function(){
                self.closeNotification();
            }, 3000);
        }
    },
    closeNotification: function() {
        var self = this;
        $(this.el).fadeOut(function() {
            self.unbind(); 
            self.remove(); 
        });
    }
});

So what this is is just a native Backbone.js view. It’s nothing too fancy, but it is specifically tailored to handle all different kinds of notifications. All you have to do to fire off a notification is to create a new instance of the view inside of whatever function you want to trigger a notification. So, for example, if you were saving a model for a book in an application, it might look something like the following…

book.save({author: "Teddy"}, {
    wait: true,
    success: function(model, response, options) {
        var success = new NotificationView({ type: 'success', text: 'Book saved successfully' });	
        ---
    }
    error: function (model, xhr, options) {
        var error = new NotificationView({ type: 'error', text: 'Error saving book' });	
        ....
    }
});

The great thing about this view is that it’s also self-closing (and also self-unbinding for the events it registers). Why is that important? One of the common problems encountered when developing Backbone.js applications around which there has been much discussion is the challenge of dealing with Backbone zombies. If you’re not sure what those are this article here is probably the most often-cited reference on the subject, but in a nutshell, when Backbone.js views bind events to particular DOM elements there arises the potential for memory leaks because those events remain in memory even though the view may no longer be present on the screen.

But fortunately for us, when it comes to this notification view, all of that is taken care of. Unless otherwise specified, the notification will fade out from the DOM after 3 seconds. A click will also close the notification.

So let’s walk through what the code can do here and why we’re doing things this way…

Options

The view takes a number of options that you can pass to the constructor as an object. If you don’t pass anything, there are some defaults defined so not to worry but you’ll definitely want to set your own messages specific to what event you are triggering the notification for. Below is how instantiation would look if you passed in all the options…

var successMessage = new NotificationView({
    type: 'success',
    text: 'You have successfully updated your profile',
    'target' '.messageBox',
    automaticClose: false
});

Below is some information on these options…

  • type
    The ‘type’ property should have the values either ‘success’, ‘error’, ‘warning’, or ‘information’. The default value is ‘information.’ The names are fairly self explanatory and should handle a lot of the cases for you
  • text
    The ‘type’ property is the actual text that will be displayed in the message. If nothing is set here, you the default text will be used depending on the “type” of message it is. So there is a default message for each type. You can change what the defaults are in the class itself.
  • target
    The ‘target’ property is the selector in DOM that you want to attach the message do. If nothing is set here, the default target will be used (and you can change this default in the class). What is nice about this is that you can have messaging in all different specific places in your application. So you could have a message localized above a specific list or input field or whatever else. It gives you a lot of flexibility to customize everything that you need.
  • automaticClose
    By default the messages all fade out and remove themselves from the DOM (and unbind their events) after 3 seconds. If the automaticClose property is set to false, then the notification will not fade out and will need to be clicked to be closed. It just gives you the option if for some reason you want your users to specifically manually remove error messages

There are probably a number of other things that could be done with this class to customize it according to the individual needs of an application, but it should give a pretty decent starting point for tackling the very important notification component that all good apps must have. What you do beyond what is presented here is entirely up to you.

More info on Backbone Views can be found here and in the Backbone.js documentation

WordPress Themes

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

1 Response to Backbone.js Notifications: The Quick and Easy Way

  1. Phah

    December 19, 2013 at 10:37 am  
    Works flawlessly, thanks!

Leave a Reply