当前位置:网站首页>Touch and take you to implement an EventEmitter
Touch and take you to implement an EventEmitter
2022-07-04 04:22:00 【Careteen】
In the daily work of cross module development , A very common scene : Event communication between different modules .
The following are given ES5、ES6 Two ways of implementation .
ES5 Realization
var events = {}
var Events = {
on: function (key, fn) {
if (typeof fn !== 'function') {
return
}
events[key] = events[key] || []
events[key].push(fn)
},
once: function (key, fn) {
if (typeof fn !== 'function' || (fn.once && fn.hasExeced)) {
return
}
fn.once = true
fn.hasExeced = false
events[key] = events[key] || []
events[key].push(fn)
},
trigger: function (key) {
var args = [].slice.call(arguments, 1)
var fnList = events[key] || []
fnList.forEach(function (item) {
if (typeof item === 'function') {
if (item.once && item.hasExeced) {
return
} else if (item.once && !item.hasExeced) {
item.hasExeced = true
item.apply(window, args)
} else {
item.apply(window, args)
}
}
})
}
}Use
ES6 Realization
subscriber
The observer
application
ultimate
For the full code, see @careteen/event-emitter
summary
边栏推荐
猜你喜欢

1289_ Implementation analysis of vtask suspend() interface in FreeRTOS

软件测试是干什么的 发现缺陷错误,提高软件的质量

leetcode刷题:二叉树08(N叉树的最大深度)

DP83848+网线热拔插

Graduation project: design seckill e-commerce system

【罗技】m720

Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?

The maximum expiration time of client secret in azure ad application registration is modified to 2 years

Leetcode skimming: binary tree 04 (sequence traversal of binary tree)

量子力学习题
随机推荐
(指针)编写函数void fun(int x,int *pp,int *n)
Three years of graduation, half a year of distance | community essay solicitation
[Yugong series] go teaching course 002 go language environment installation in July 2022
How to add custom API objects in kubernetes (1)
批处理初识
Understand the principle of bytecode enhancement technology through the jvm-sandbox source code
02 ls 命令的具体实现
R语言中如何查看已安装的R包
[webrtc] M98 Ninja build and compile instructions
【罗技】m720
如何远程办公更有效率 | 社区征文
Leetcode skimming: binary tree 04 (sequence traversal of binary tree)
ctf-pikachu-XSS
【微服务|openfeign】feign的两种降级方式|Fallback|FallbackFactory
Redis:集合Set类型数据的操作命令
Leetcode skimming: binary tree 07 (maximum depth of binary tree)
hbuildx中夜神模拟器的配置以及热更新
[csrf-01] basic principle and attack and defense of Cross Site Request Forgery vulnerability
JDBC advanced
三年进账35.31亿,这个江西老表要IPO了