什么是“事件发射器"?

浏览 http://microjs.com,我看到很多标有事件发射器"的库.我喜欢认为我非常了解 Javascript 语言的基础知识,但我真的不知道事件发射器"是什么或做什么.

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.

有人愿意给我解惑吗?听起来很有趣……

Anyone care to enlighten me? It sounds interesting...

推荐答案

它触发一个 事件 任何人都可以收听.不同的库提供不同的实现和不同的目的,但基本思想是提供一个框架来发布事件和订阅它们.

It triggers an event to 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.

来自 jQuery 的示例:

Example from jQuery:

// Subscribe to event.
$('#foo').bind('click', function() {
    alert("Click!");
});

// Emit event.
$('#foo').trigger('click');

然而,使用 jQuery 要发出事件,您需要有一个 DOM 对象,并且不能从任意对象发出事件.这就是事件发射器变得有用的地方.这是一些用于演示自定义事件的伪代码(与上面完全相同的模式):

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):

// 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");

相关文章