首页 > 其他 > 详细

实现vue中的$on $emit

时间:2019-03-10 16:44:11      阅读:494      评论:0      收藏:0      [点我收藏+]
    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!

 

实现vue中的$on $emit

原文:https://www.cnblogs.com/codejoker/p/10505516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!