什么是“事件发射器"?

What is an quot;event emitterquot;?(什么是“事件发射器?)
本文介绍了什么是“事件发射器"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

浏览 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");

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)