We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
一个比较常见的功能,非常有利于代码解耦,直接上代码。
;(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指定
……
The text was updated successfully, but these errors were encountered:
No branches or pull requests
一个比较常见的功能,非常有利于代码解耦,直接上代码。
实现的接口
具体实现
测试
其他需求
回调函数的this指向可以通过bind指定
……
The text was updated successfully, but these errors were encountered: