Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现自定义事件 #5

Open
Cyrilszq opened this issue Feb 9, 2017 · 0 comments
Open

实现自定义事件 #5

Cyrilszq opened this issue Feb 9, 2017 · 0 comments

Comments

@Cyrilszq
Copy link
Owner

Cyrilszq commented Feb 9, 2017

一个比较常见的功能,非常有利于代码解耦,直接上代码。

实现的接口

  • on(eventName,handler),绑定事件
  • emit(eventName,arguments),触发事件
  • once(eventName,handler),绑定只执行一次的事件
  • off(eventName),解除事件绑定

具体实现

;(function (window) {
     function EventProxy() {
        this.handlers = {} // 存放所有添加的事件
    }

    EventProxy.prototype = {
        on: function (eventName, handler) {
            this.handlers[eventName] = this.handlers[eventName] || [];
            this.handlers[eventName].push(handler);
        },
        once: function (eventName, handler) {
            var self = this
            // 改写原回调,使执行一次后删除
            var wrapper = function () {
                handler.apply(self, arguments);
                self.off(eventName, wrapper);
            };
            this.on(eventName, wrapper)
        },
        emit: function (eventName) {
            var args = Array.prototype.slice.call(arguments, 1) // 取出传入的参数
            for (var i = 0,len = this.handlers[eventName].length; i < len; i++) {
                this.handlers[eventName][i].apply(this, args);
            }
        },
        off: function (eventName, handler) {
            var handlers = this.handlers[eventName],i
            if (handlers && handler) {
                i = handlers.indexOf(handler)
                handlers.splice(i, 1)
            }else {
                this.handlers[eventName] = []
            }
        }
    }   

    window.EventProxy =  EventProxy
})(window)

测试

var ep = new EventProxy ()
ep.on("event1",function () {
    console.log("event1 emit 1")
})

ep.emit("event1")  // event1 emit 1

ep.on("event1",function (value) {
    console.log("event1 emit " + value)
})

ep.emit("event1","一些参数") // event1 emit 1
                            // event1 emit 一些参数

ep.once("event2",function (value) {
    console.log("event2 emit once " + value)
})

ep.emit("event2", "一些参数") // event2 emit once 一些参数
ep.emit("event2", "一些参数") 
ep.off("event1")
ep.emit("event1")  

其他需求

回调函数的this指向可以通过bind指定

……

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant