實現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!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM