Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - What is an "event emitter"?

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...