virtualstory / blog

my github issues blog
MIT License
0 stars 0 forks source link

js中的发布订阅模式 #3

Open virtualstory opened 5 years ago

virtualstory commented 5 years ago
"use strict";

function Observer() {
    this.handlers = {};
}

Observer.prototype = {
    constructor: Observer,
    on: function(type, handler) {
        if(!(type in this.handlers)) {
            this.handlers[type] = [];
        }
        this.handlers[type].push(handler);
        return this;
    },
    emit: function(type) {
        var typeHandlers = this.handlers[type];
        if(typeHandlers) {
            var args = Array.prototype.slice.call(arguments, 1);
            var len = typeHandlers.length;
            var i = 0;
            for(;i < len; i++) {
                typeHandlers[i].apply(this, args);
            }
        }
        return this;
    },
    off: function(type, handler) {
        var typeHandlers = this.handlers[type];
        if(typeHandlers) {
            if(!handler) {
                delete this.handlers[type];
            } else {
                var len = typeHandlers.length;
                var i = len - 1;
                for(;i >= 0; i--) {
                    if(typeHandlers[i] === handler) {
                        typeHandlers.splice(i, 1);
                    }
                }
            }
        }
        return this;
    }
};

var ob = new Observer();
ob.on('change', function(data) {
    console.log('change handler one: ', data);
});
ob.on('change', function(data) {
    console.log('change handler two: ', data);
});
ob.emit('change', 'first emit args');
// change handler one:  first emit args
// change handler two:  first emit args
ob.emit('change', 'second emit args');
// change handler one:  second emit args
// change handler two:  second emit args