What is `emit` javascript function?
Asked Answered
N

3

17

While looking through sax nodejs module, i saw multiple emit function calls, but i can't find any information about it.

Is it some V8 native tool for emitting events? Why sax-js do not use EventEmitter for streams then?

Neonatal answered 27/8, 2015 at 9:57 Comment(0)
M
5

Please look at line number 624 of the same file.

function emit (parser, event, data) {

  parser[event] && parser[event](data)

}
Michell answered 27/8, 2015 at 10:2 Comment(0)
V
31

In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted.

The on or addListener method (basically the subscription method) allows you to choose the event to watch for and the callback to be called. The emit method (the publish method), on the other hand, allows you to "emit" an event, which causes all callbacks registered to the event to 'fire', (get called).

reference: https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-event-emitters/ (This is an outdated link and doesn't work anymore)

Vollmer answered 27/8, 2015 at 10:2 Comment(0)
A
13

Short: Emit's job is to trigger named event(s) which in turn cause functions called listeners to be called.

Detailed: Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") periodically emit named events that cause Function objects ("listeners") to be called.

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and will be discarded.

Read More here

Amero answered 4/4, 2018 at 5:29 Comment(0)
M
5

Please look at line number 624 of the same file.

function emit (parser, event, data) {

  parser[event] && parser[event](data)

}
Michell answered 27/8, 2015 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.