实现vue中的$on $emit

    var eventList = {
            'sayName': [sayName]
        }
        var name = 'hehe'
        var age = 28
        function sayName() {
            console.log(this.name)
        }
        function sayAge() {
            console.log(this.age)
        }
        function $on(type, fn) {
            if (!this.eventList[type]) {
                this.eventList[type] = []
            }
            this.eventList[type].push(fn)
        }
        function $emit() {
            let type = Array.prototype.shift.call(arguments)
            let onCallbacks = eventList[type]
            onCallbacks.forEach(element => {
                element.apply(this, arguments)
            });
        }
        $emit('sayName') // hehe
        $on('sayAge', sayAge)
        $emit('sayAge') // 28
        $on('sayHello', (arg) => console.log(arg+ ', Hello!'))
        $emit('sayHello', 'John') // John, Hello!

 

posted on 2019-03-10 15:38  时光游弋  阅读(1184)  评论(0编辑  收藏  举报