Javascript Patterns Mediator vs Observer

javascript Nov 4, 2013

An approach to separating your Ajax requests from your DOM is to use messaging. Messaging allows different parts of an application to communicate with each other without knowing that the others even exist. This means that various pieces of the application are hot swapable! So, if you have an Ajax request class that is separate from your DOM logic, all you have to do to change the Ajax logic is, change the Ajax logic. You don't have to go fishing through all the places that your Ajax piece was used. Instead just change it in one place and it's done.

There are different types of messaging patterns such as observer, and mediator. In either pattern there would be some object emitting messages (or events). In observer based messaging, it might look like...

var user = new User();

var app = {
    init: function() {
        user.on( "login", this.userLoggedIn );
    },
    userLoggedIn: function() {
        // user is now logged in.
    }
};
app.init();

// somewhere else in the app
user.trigger( "login" );

So, in this example, the app has a direct reference to the user so you can say, "the app is observing the events on the user".

Using the mediator pattern would look like...

// the user is some kind of an emitter
var user = new User();

var app = {
    events: new SomeKindOfEmitter(),
    init: function() {
        app.events.on( "login", this.userLoggedIn );
    },
    userLoggedIn: function() {
        // user is now logged in.
    }
};
app.init();

// somewhere else in the app
app.events.trigger( "login" );

Using a mediator allows the app logic to be separated from the user logic. This could also allow any other object in the application to listen for the login event by just listening for events triggered from app.events.

Tags