当前位置:网站首页>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
边栏推荐
猜你喜欢

Activiti7 task service - process variables (setvariable and setvariablelocal)

Flink学习7:应用程序结构

leetcode刷题:二叉树04(二叉树的层序遍历)

Global exposure and roller shutter exposure of industrial cameras

Rhcsa-- day one

Two commonly used graphics can easily realize data display

毕业设计项目

Graduation project: design seckill e-commerce system

Restore the subtlety of window position

拼夕夕二面:说说布隆过滤器与布谷鸟过滤器?应用场景?我懵了。。
随机推荐
[csrf-01] basic principle and attack and defense of Cross Site Request Forgery vulnerability
Redis cluster view the slots of each node
【华为云IoT】读书笔记之《万物互联:物联网核心技术与安全》第3章(上)
Leetcode brush question: binary tree 06 (symmetric binary tree)
批处理初识
*. No main manifest attribute in jar
思考的小记录
R语言dplyr中的Select函数变量列名
指针数组和数组指针
C language bidirectional linked list first edition
华为云鲲鹏工程师培训(广西大学)
Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
[Logitech] m720
Introduction to asynchronous task capability of function calculation - task trigger de duplication
leetcode刷题:二叉树04(二叉树的层序遍历)
Leetcode skimming: binary tree 08 (maximum depth of n-ary tree)
Spa in SDP
【CSRF-01】跨站请求伪造漏洞基础原理及攻防
【读书会第十三期】多媒体处理工具 FFmpeg 工具集
Perf simple process for multithreaded profile