Event messaging between JavaScript objects.

Simplest implementation:

function NewMessageBus() {
    return {
        when: function(name, fn) {
            this.fire[name] = fn;
        },
        fire: {}
    };
}

var msgBus = NewMessageBus();

Usage of this requires two things:

Creating the event

var presenter = (function() {
    msgBus.when('getContent', function() {
        model.load(view.content);
    });
}());

Note that the presenter is state-less.

Firing the event

var view = {
    getContent: function() {
        msgBus.fire.getContent();
    },
    content(htmlData) {
        $('#contentContainer').html(htmlData);
    }
}

var model = {
    load: function(cb) {
        $.ajax({
            type:       'GET',
            url:        'myContent.php',
            dataType:   'json',
            data:       {/* some parameters */},
            success:    function(data) {
                // some preprocessing of data
                cb(data.html);
                // some post processing of data
        });
    }
}

Usage

view.getContent();

That’s it pretty simple.

The view/model does not have any references to each other.

About these ads

Tags: , ,

One Response to “Event messaging between JavaScript objects.”

  1. Javascript Examples Says:

    that’s all cool tips, thank you very much for sharing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 203 other followers

%d bloggers like this: