Javascript 什么是“事件发射器”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13438924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is an "event emitter"?
提问by wwaawaw
Browsing through http://microjs.com, I see lots of libraries labelled "event emitters". I like to think I know my way around the basics of the Javascript language pretty well, but I really have no idea what an "event emitter" is or does.
浏览http://microjs.com,我看到很多标有“事件发射器”的库。我喜欢认为我非常了解 Javascript 语言的基础知识,但我真的不知道“事件发射器”是什么或做什么。
Anyone care to enlighten me? It sounds interesting...
有人关心启发我吗?听起来很有趣...
采纳答案by niaher
It triggers an eventto which anyone can listen. Different libraries offer different implementations and for different purposes, but the basic idea is to provide a framework for issuing events and subscribing to them.
它触发一个任何人都可以收听的事件。不同的库提供不同的实现和不同的目的,但基本思想是提供一个框架来发布事件和订阅它们。
Example from jQuery:
来自 jQuery 的示例:
// Subscribe to event.
$('#foo').bind('click', function() {
alert("Click!");
});
// Emit event.
$('#foo').trigger('click');
However, with jQuery in order to emit an event you need to have a DOM object, and cannot emit events from an arbitrary object. This is where event-emitter becomes useful.Here's some pseudo-code to demo custom events (the exact same pattern as above):
但是,使用 jQuery 来发出事件,您需要有一个 DOM 对象,并且不能从任意对象发出事件。这是事件发射器变得有用的地方。下面是一些演示自定义事件的伪代码(与上面的模式完全相同):
// Create custom object which "inherits" from emitter. Keyword "extend" is just a pseudo-code.
var myCustomObject = {};
extend(myCustomObject , EventEmitter);
// Subscribe to event.
myCustomObject.on("somethingHappened", function() {
alert("something happened!");
});
// Emit event.
myCustomObject.emit("somethingHappened");
回答by Rahul Tripathi
In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted.
在 node.js 中,事件可以简单地描述为带有相应回调的字符串。一个事件可以被多次“发出”(或者换句话说,相应的回调被调用)或者你可以选择只在它第一次发出时监听。
Example:-
例子:-
var example_emitter = new (require('events').EventEmitter);
example_emitter.on("test", function () { console.log("test"); });
example_emitter.on("print", function (message) { console.log(message); });
example_emitter.emit("test");
example_emitter.emit("print", "message");
example_emitter.emit("unhandled");
> var example_emitter = new (require('events').EventEmitter);
{}
> example_emitter.on("test", function () { console.log("test"); });
{ _events: { test: [Function] } }
> example_emitter.on("print", function (message) { console.log(message); });
{ _events: { test: [Function], print: [Function] } }
> example_emitter.emit("test");
test //console.log'd
true //return value
> example_emitter.emit("print", "message");
message //console.log'd
true //return value
> example_emitter.emit("unhandled");
false //return value
This demonstates all the basic functionality of an EventEmitter. The on or addListenermethod (basically the subscription method) allows you to choose the event to watch for and the callback to be called. The emitmethod (the publish method), on the other hand, allows you to "emit" an event, which causes all callbacks registered to the event to 'fire', (get called).
这演示了EventEmitter. 该on or addListener方法(基本上是订阅方法)允许您选择要监视的事件和要调用的回调。emit另一方面,该方法(发布方法)允许您“发出”一个事件,这会导致注册到该事件的所有回调“触发”(被调用)。
From the source What are Event Emitters?
从源头什么是事件发射器?
回答by Eldiyar Talantbek
Simple example in Node.js:
Node.js 中的简单示例:
var EventEmitter = require('events').EventEmitter;
var concert = new EventEmitter;
var singer = 'Coldplay';
concert.on('start', function (singer) {
console.log(`OMG ${singer}!`);
});
concert.on('finish', function () {
console.log(`It was the best concert in my life...`);
});
concert.emit('start', singer);
concert.emit('finish');
回答by Vinayak Trivedi
Consider a call-back function-
考虑一个回调函数——
function test(int a, function(){
console.log("I am call-back function");
}){
console.log("I am a parent function");
}
Now, whenever the parent function is called on an event(a button click or any connection etc) , it first executes its code, and then control is passed to the call-back function. Now, an event emitter is an object/method which triggers an event as soon as some action takes place so as to pass the cntrol to the parent function. For-example- Server is an event emitter in Node.Js programming. It emits event of error as soon as the server encounters an error which passes the control to error parent function. Server emits an event of connection as soon as a socket gets connected to server, this event then triggers the parent function of getConnections, which indeed also takes a call-back function as argument. So, it indeed is a chain, which is triggered as something happens by event emitter which emits an event to start a function running.
现在,每当在事件(按钮单击或任何连接等)上调用父函数时,它首先执行其代码,然后将控制传递给回调函数。现在,事件发射器是一个对象/方法,一旦某些动作发生,它就会触发一个事件,以便将控制传递给父函数。例如,Server 是 Node.Js 编程中的事件发射器。一旦服务器遇到错误,它将控制传递给错误父函数,它就会发出错误事件。一旦套接字连接到服务器,服务器就会发出连接事件,然后该事件触发 getConnections 的父函数,该函数确实也将回调函数作为参数。所以,它确实是一个链,当事件发射器发生某些事情时触发它,它发出一个事件来启动一个函数运行。

