JavaScript Observer Class

The observer pattern is a one to many relationship that involves publishers and subscribers. Or rather, observers and its subject.

Go ahead and click on the first item, and notify your subscribers. Take note of the result. Then click the second item to unsubscribe a particular member. Now go back and click the first.

function Observer() {
    this.fns = [];
}
Observer.prototype = {
    subscribe : function(fn) {
        this.fns.push(fn);
    },
    unsubscribe : function(fn) {
        this.fns = this.fns.filter(
            function(el) {
                if ( el !== fn ) {
                    return el;
                }
            }
        );
    },
    fire : function(o, thisObj) {
        var scope = thisObj || window;
        this.fns.forEach(
            function(el) {
                el.call(scope, o);
            }
        );
    }
};