Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
44
rated 0 times [  47] [ 3]  / answers: 1 / hits: 69867  / 12 Years ago, sun, november 18, 2012, 12:00:00

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


More From » events

 Answers
0

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

[#81930] Friday, November 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deonkalvinw

Total Points: 409
Total Questions: 96
Total Answers: 89

Location: Saint Pierre and Miquelon
Member since Sun, Nov 27, 2022
2 Years ago
deonkalvinw questions
Sun, Feb 6, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Sun, Aug 22, 21, 00:00, 3 Years ago
Sun, Mar 7, 21, 00:00, 3 Years ago
;