Observer

function Observer{
        this.listeners = [];
 
        this.subscribe = function(callback, event) {
            event = event || 'any';
            if (typeof this.listeners[event] === "undefined") {
                this.listeners[event] = [];
            }
            this.listeners[event].push(callback);
        };
 
        this.unsubscribe = function(fn, event) {
            event = event || 'any';
            var subs = this.listeners[event] || [];
            for (var i = 0, max = subs.length; i < max; i += 1) {
                if (subs[i] === fn) {
                    subs.splice(i, 1);
                }
            }
        };
 
        this.publish = function(data, event) {
            event = event || 'any';
            var subs = this.listeners[event] || [];
            for (var i = 0, max = subs.length; i < max; i += 1) {
                subs[i](data, event);
            }
        };
 
    }
 
var obs = new Observer();
 
obs.subscribe(function(data, event) {
        console.log(data);
    }, "specListLoaded");
 
obs.publish([1,2], "specListLoaded");
 
/disk_1/www/cz/ladariha/wiki/data/pages/programovani/javascript/observer.txt · Poslední úprava: 2013/07/07 23:14 autor: ladariha
 
Kromě míst, kde je explicitně uvedeno jinak, je obsah této wiki licencován pod následující licencí:CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki