Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackboneJS Flash Messages

Tags:

backbone.js

Is there an extension to backbone for Flash Messages? It seems to be a common feature in Web Frameworks (server side at least). There appears to be none, and I attempted to make my own:

class FlashMessenger extends Backbone.Model 

    constructor: ->
        @messages = []

    # add a message to the messages array
    add: (type, message) ->
        @messages.push 
            type: type
            message: message

    # returns all existing messages and clearing all messages
    getMessages: ->
        ret = @messages.slice(0)
        @messages = []
        return ret

Now, I was wondering how can I inject them into my views automatically. I will like my messages to show when I use Backbone.Router.navigate() eg:

app.flashMessages.add("success", "Successfully logged in")
appRouter.navigate("dashboard")
# flash messages should show when I render the view
like image 864
Jiew Meng Avatar asked Jun 24 '12 14:06

Jiew Meng


1 Answers

My 5 cents -- it seems to be a bit of an overkill to use Backbone for flash messages. If you have only 1 instance of flash message on the page, you're better off not using a separate model for it.

Instead I would use a view for Flash message and a global dispatcher:

Dispatcher = _.extend({}, Backbone.Events);

Create view:

var FlashMessage = Backbone.View.extend({
    initialize: function() {
       Dispatcher.bind('show_flash_message', this.render);
    },

    render: function(msg) {
       // do something with the message
    }
});

And from the part of the app where you have to show the flash message, do

Dispatcher.trigger('show_flash_message', 'Some message');
like image 111
mvbl fst Avatar answered Oct 22 '22 01:10

mvbl fst