Posts Tagged ‘decoupling’

Event messaging between JavaScript objects.

June 12, 2010

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.