美文网首页
发布订阅(第2天)

发布订阅(第2天)

作者: 不吃鱼的猫_8e95 | 来源:发表于2018-09-15 19:34 被阅读0次
//发布 emit 订阅 on  {失恋:['哭','吃','购物']}
//一对多 多对一的关系

function Girl() { //创建对象

    this._events = {} //对象的事件集合

} // {失恋:[cry]}

Girl.prototype.on = function (eventName, callback) { //订阅
    if (this._events[eventName]) { //判断是不是第一次--不是第一次
        this._events[eventName].push(callback); //{失恋:[cry,eat,shopping]}
    } else {
        this._events[eventName] = [callback] //{失恋:[cry]
    }

};

Girl.prototype.emit = function (eventName, ...args) { //发布

    if (this._events[eventName]) {
        this._events[eventName].forEach(cb => cb.apply(this, args));

        // forEach(cb=>cb(...args));
    }

};


let girl = new Girl();

let cry = (who) => {
    console.log(who + '哭')
};

let eat = (who) => {
    console.log(who + '吃')
};

let shopping = (who) => {
    console.log(who + '购物')
};


girl.on('失恋', cry); // {失恋:[cry]
girl.on('失恋', eat); //{失恋:[cry,eat]
girl.on('失恋', shopping); //{失恋:[cry,eat,shopping]

girl.emit('失恋', '我', '你');

相关文章

网友评论

      本文标题:发布订阅(第2天)

      本文链接:https://www.haomeiwen.com/subject/rvocmftx.html