自定义事件

// (来自JavaScript高级程序设计) 自定义事件
function EventTarget() {
    this.handler = {};
}



EventTarget.prototype = {
    constructor: EventTarget,

    // 添加事件
    addHandler: function (type, fn) {
        if (!this.handler[type]) this.handler[type] = [];
        this.handler[type].push(fn);
    },

    // 删除事件
    removeHandler: function (type) {
        if (this.handler[type]) delete this.handler[type];
    },

    // 执行事件
    fire: function (event) {
        if (!event.target) event.target = this;
        if (Array.isArray(this.handler[event.type])) {
            var handlers = this.handler[event.type];
            for (var i = 0, len = handlers.length; i < len; i ++) {
                handlers[i](event);
            }
        }
    }
};
原文地址:https://www.cnblogs.com/shanchenba/p/5646812.html