本文介绍了浏览器端是否有任何在nodejs中具有类似逻辑的EventEmitter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在node.js中使用eventEmitter很容易:
It is so easy to use eventEmitter in node.js:
var e = new EventEmitter();
e.on('happy', function(){console.log('good')});
e.emit('happy');
浏览器本机中的任何客户端EventEmitter吗?
Any client side EventEmitter in browser native?
推荐答案
在现代浏览器中,存在EventTarget.
In modern browsers, there is EventTarget.
class MyClass extends EventTarget {
doSomething() {
this.dispatchEvent(new Event('something'));
}
}
const instance = new MyClass();
instance.addEventListener('something', (e) => {
console.log('Instance fired "something".', e);
});
instance.doSomething();
其他资源:
-
Maga Zandaqo在此处提供了出色的详细指南: https://medium.com/@zandaqo/eventtarget-the-future-of-javascript-event-systems-205ae32f5e6b
MDN有一些文档: https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget
MDN has some documentation: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
针对Safari和其他无法运行的浏览器的填充: https://github.com/ungap/event-target
Polyfill for Safari and other incapable browsers: https://github.com/ungap/event-target
这篇关于浏览器端是否有任何在nodejs中具有类似逻辑的EventEmitter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!