2010
06.21

On a previous project we were writing a web UI using a lot of javascript. The UI was constructed in an MVP style with many Views, Presenters and Models all active at the same time. One of the problems we had was with having multiple Presenters subscribed to listen for a single callback from a Model.

Initially we had quite an ugly solution which involved chaining functions in a similar fashion as to DOM events were handled in the pre jQuery days. To do this we used the following function…

function addEventHandler(event, scope, method) {
    var oldEvent = event;
    return function() {

        var params = [];
        for (var i = 0; i < arguments.length; i++) {
            params.push(arguments[i]);
        }
        params.push(this);
        oldEvent.apply(this, params);
        method.apply(scope, params);
    };
}

Example usage…

someObject.someEvent = addEventHandler(someObject.someEvent, this, doSomething);
function doSomething() {
}

After some refactoring we created an Event class (semi inspired by Node.Js EventEmitter). This seemed like a nice way to allow us to simplify the syntax, make it easier to read and attempt to use a familiar syntax to listeners else where in JavaScript.

var Event = function() {
    var self = this;
    var handlers = [];

    self.addListener = function(handler) {
        handlers.push(handler);
    };

    self.trigger = function() {
        for(var index in handlers) {
            handlers[index].apply(this, getArguments(arguments));
        }
    };

    var getArguments = function(args) {
        var params = [];
        for (var i = 0; i < args.length; i++) {
            params.push(args[i]);
        }
        return params;
    };
};

Example usage…

someObject.someEvent.addListener(doSomething);
function doSomething() {
}

No Comment.

Add Your Comment