js自定义绑定事件

function Boy() {
    this._events = {};//定义的是对象
}
Boy.prototype.on = function (eventName, callback) {
    if (this._events[eventName]) {//不是第一次
        let flag = false;
        this._events[eventName].forEach((cb) => {
            if (cb == callback) flag = true;
        })
        if (!flag) {//防止重复绑定
            this._events[eventName].push(callback);
        }
    } else {
        this._events[eventName] = [callback];
    }
};
Boy.prototype.emit = function (eventName) {
    if (this._events[eventName]) {
        this._events[eventName].forEach(cb => cb())
    }
};

let play = function () {
    console.log("玩")
};

let eat = function () {
    console.log("吃")
};

let test = () => {
    console.log("测试箭头函数")
}

let boy = new Boy();
boy.on('doPlay', play);
boy.on('doPlay', test);
boy.emit('doPlay');

猜你喜欢

转载自my.oschina.net/u/2426590/blog/1818429