什么是“事件发射器”? [英] What is an "event emitter"?

查看:118
本文介绍了什么是“事件发射器”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览 http://microjs.com ,我看到很多标有事件发射器的图书馆。我喜欢认为我知道我的JavaScript语言的基本知识很好,但我真的不知道什么是事件发射器是或是。

Browsing through http://microjs.com, I see lots of libraries labeled "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...

推荐答案

事件发射器听起来只是触发任何人可以听的事件。不同的库提供不同的实现和不同的目的,但基本思想是提供发布事件和订阅的框架。

Event emitter as it sounds is just something that 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");

这篇关于什么是“事件发射器”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆