← home ← blog

Using jQuery custom events in your Object Literal and Observer Pattern applications

03 December 2012

Harnessing jQuery’s cooler features in your application can really enhance the performance and, sometimes more importantly, the maintainability of your web application.

The short snippet below utilises the Observer Pattern and the Object Literal Pattern. To read more about these and other Design Patterns, I can’t recommend Addy Osmani’s excellent “Learning JavaScript Design Patterns” enough.

Firstly, the snippet.

var app = {};

app.mediator = $({});

app.walt = {
    init: function() {
        app.mediator.on('yo', this.yo)
    },

    yo: function(event, params) {
        console.log(params.name);
    }
}

app.hank = {
    init: function() {
        var data = {
            name: 'jesse pinkman'
        };
        app.mediator.trigger('yo', data);
    }
}

app.walt.init();
app.hank.init();

What the above does, is uses an intermediary Object to handle the Publishing (triggering) and the Subscribing (on) of messages and data within your application. You may sometimes see the Observer Pattern being referred to as “PubSub” - this is simply short for Publisher/Subscriber.

Advantages of using this pattern are that you can remove objects from your code and things won’t break. Each object doesn’t have a working knowledge of how any other objects work, it just blindly sends messages and listens out for messages, reacting to those events.

The result is a nice, decoupled application with a handsome degree of separation of concerns.

I'm available for hire

Hire me