$emit $on 的实现

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!

你可能感兴趣的:(js学习,js,vue,框架)