Node.js, EventEmitter of why using it - node.js

I have a question about events.EventEmitter in Node.js, why use it? What is the difference with example 1 and example 2? I find them identical, are they? When is it practical to use it?
let events = require("events");
let util = require("util");
let eventEmitter = new events.EventEmitter();
Example 1 with the EventEmitter:
let Student = function(name) {
this.name = name;
}
util.inherits(Student, events.EventEmitter);
let student_max = new Student('max');
student_max.on('scored', function(points) {
if (points > 90) {
points = points + ' wow you scored more than 90'
}
console.log(`${this.name} ${points} points`);
})
student_max.emit('scored',95);
Example 2 without EventEmitter
let Student2 = function(name) {
this.name = name;
this.score = function(str,points) {
if (str!=='scored') {
return;
}
if (points > 90) {
points = points + ' wow you scored more than 90'
}
console.log(`${this.name} ${points} points`);
}
}
let student_lenny = new Student2('Lenny');
student_lenny.score('scored',95);

The first example subclasses an event emitter and then uses that event emitter to implement some functionality. That means that anyone else can take one of your student_max objects and register an event listener for the scored message or they could even emit a scored message themselves. You could then very easily use the eventEmitter functionality to extend to other events that occurred in your object and then any third party could observe or trigger those events too. eventEmitter is a standardized way of exposing event based functionality. You can accomplish things with an eventEmitter by designing your own notification schemes, but it is often better to build on a standard scheme that lots of developers already know and that has a fair amount of functionality already built in.
Your second example as currently coded accomplishes the same thing, but is not as extensible. For example, if you wanted to know anything a score happens, you would have to subclass the object and override the score method rather than just adding a listener to an event using the well-established eventEmitter interface. If you didn't create the object yourself (which makes it hard to subclass), then you'd have to monkey-patch the score method in order to observe it.
what is the difference of the example1 to example2
It's an architectural difference that affects both how outside agents interact with these objects and how extensible they are in the future.
The use of the eventEmitter in example1 is very extensible and makes it easy to add future events to the object using the eventEmitter features or for outside agents to monitor or trigger events using a standardized interface. So, the difference is not in exactly what the code you show achieves, but in how it is architected and thus how extensible it would be in the future or how outside code could interact with your object
When is it practical to use it?
You would think about using an eventEmitter object pretty much anytime you want outside parties to be able to observe events or trigger events on your object in a lightweight and easy way. It's a pre-built system for that and is often better than inventing your own callback notification scheme. And sometimes, it is useful even for your own implementation when you aren't trying to enable outside interactions.

Related

Chaining .emit( ) with EventListener in Node.js

When using the EventEmitter class in Node.js what is the best practice way to chain together different events?
Let's say I have multiple events, and I want to emit/trigger event 'B' but only inside the listener of some other initial event, 'A'. I was able to do something like that below, I'm just wondering if it is correct / memory-efficient to reference the eventEmitter instance in its own event listeners?
import {EventEmitter} from 'events';
const eventEmitter = new EventEmitter();
const eventTypes = ['txRequestReceived', 'txRequestComplete'];
eventEmitter.on('txRequestReceived', (params)=>{
let {chainID, address} = params;
console.log(`txRequestReceived event: ${chainID} -- ${address}`);
eventEmitter.emit('txRequestComplete', {"chainID": chainID, "address": address});
});
eventEmitter.on('txRequestComplete', (params)=>{
let {chainID, address} = params;
console.log(`txRequestComplete event: ${chainID} -- ${address}`);
});
This does work, and I'm able to pass around an event payload with the listener parameters. I'm wondering if there are memory / scope issues with it? If I were to write a class and extend the EventEmitter class, would I just use the 'this' keyword to access .emit() and .on() behaviour?
I was able to find this "answer" (which I will accept). The pattern I used works, but there are caveats surrounding the fact that EventEmitter is synchronous and how closures with the handlers may handle memory.
https://www.codementor.io/#simenli/demystifying-asynchronous-programming-part-2-node-js-eventemitter-7r51ivby4

What is the difference between using the EventEmitter and just using functions?

As you can tell from this question, I'm very new to Node.js. If a question like this is not suited for this forum I do apologize and request that you direct me to a better place please.
I'm watching some training courses on Lynda and we are covering the EventEmitter. In the code below we have to add an event to the Person object. My question is, why add this event this way and not just add a function called speak to the Person object from the start? Thank you very much!
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Person = function(name) {
this.name = name;
};
util.inherits(Person, EventEmitter);
var ben = new Person("Ben Franklin");
ben.on('speak', function(said) {
console.log(`${this.name}: ${said}`);
});
ben.emit('speak', "You may delay, but time will not.");
EventEmitter is helpful when you can't control (much) the generation of events. They can be caused by some asynchronous operation which you don't control. For example, a database disconnecting.
Here in the example, event is Ben speaking something. You don't control Ben.
You can respond to his event by defining a listener - a function which executes whenever the said event occurs.

Flux - Isn't it a bad practice to include the dispatcher instance everywhere?

Note: My question is about the way of including/passing the dispatcher instance around, not about how the pattern is useful.
I am studying the Flux Architecture and I cannot get my head around the concept of the dispatcher (instance) potentially being included everywhere...
What if I want to trigger an Action from my Model Layer? It feels weird to me to include an instance of an object in my Model files... I feel like this is missing some injection pattern...
I have the impression that the exact PHP equivalent is something (that feels) horrible similar to:
<?php
$dispatcher = require '../dispatcher_instance.php';
class MyModel {
...
public function someMethod() {
...
$dispatcher->...
}
}
I think my question is not exactly only related to the Flux Architecture but more to the NodeJS "way of doing things"/practices in general.
TLDR:
No, it is not bad practice to pass around the instance of the dispatcher in your stores
All data stores should have a reference to the dispatcher
The invoking/consuming code (in React, this is usually the view) should only have references to the action-creators, not the dispatcher
Your code doesn't quite align with React because you are creating a public mutable function on your data store.
The ONLY way to communicate with a store in Flux is via message passing which always flows through the dispatcher.
For example:
var Dispatcher = require('MyAppDispatcher');
var ExampleActions = require('ExampleActions');
var _data = 10;
var ExampleStore = assign({}, EventEmitter.prototype, {
getData() {
return _data;
},
emitChange() {
this.emit('change');
},
dispatcherKey: Dispatcher.register(payload => {
var {action} = payload;
switch (action.type) {
case ACTIONS.ADD_1:
_data += 1;
ExampleStore.emitChange();
ExampleActions.doThatOtherThing();
break;
}
})
});
module.exports = ExampleStore;
By closing over _data instead of having a data property directly on the store, you can enforce the message passing rule. It's a private member.
Also important to note, although you can call Dispatcher.emit() directly, it's not a good idea.
There are two main reasons to go through the action-creators:
Consistency - This is how your views and other consuming code interacts with the stores
Easier Refactoring - If you ever remove the ADD_1 action from your app, this code will throw an exception rather than silently failing by sending a message that doesn't match any of the switch statements in any of the stores
Main Advantages to this Approach
Loose coupling - Adding and removing features is a breeze. Stores can respond to any event in the system with by adding one line of code.
Less complexity - One way data flow makes wrapping head around data flow a lot easier. Less interdependencies.
Easier debugging - You can debug every change in your system with a few lines of code.
debugging example:
var MyAppDispatcher = require('MyAppDispatcher');
MyAppDispatcher.register(payload => {
console.debug(payload);
});

What language level support (if any) does Swift have for asynchronous programming?

Asynchronous programming is a must for responsive user interfaces when application have to communicate over unpredictable networks (e.g. smart phone applications). The user interface must remain responsive while waiting for results to come back from servers somewhere over the internet.
In most languages, the application programmer has to implement their own state machines (maybe using closures) to respond to asynchronous callbacks and/or coordinate multiply threads using locks.
Both of these are very error prone and not for the fait hearted!
(c# introduced the async keyword to help with this, only time (at least 5 years) will tell if it is a good solution.)
Does Swift have any built in support to assist the writing of asynchronous code?
While it isn't a built-in language feature, it may be interesting to note that it's possible to implement C# style async/await for Swift, and that because of the special syntax afforded to the last closure argument of a function call, it even looks like it might be part of the language.
If anyone is interested, you can get code for this on Bitbucket. Here's a quick taster of what's possible:
let task = async { () -> () in
let fetch = async { (t: Task<NSData>) -> NSData in
let req = NSURLRequest(URL: NSURL.URLWithString("http://www.google.com"))
let queue = NSOperationQueue.mainQueue()
var data = NSData!
NSURLConnection.sendAsynchronousRequest(req,
queue:queue,
completionHandler:{ (r: NSURLResponse!, d: NSData!, error: NSError!) -> Void in
data = d
Async.wake(t)
})
Async.suspend()
return data!
}
let data = await(fetch)
let str = NSString(bytes: data.bytes, length: data.length,
encoding: NSUTF8StringEncoding)
println(str)
}
Also, if you want something like #synchronized, try this:
func synchronized(obj: AnyObject, blk:() -> ()) {
objc_sync_enter(obj)
blk()
objc_sync_exit(obj)
}
var str = "A string we can synchronise on"
synchronized(str) {
println("The string is locked here")
}
Swift's approach to asynchronous programming is the same as Objective C's: use Grand Central Dispatch. You can pass closures to gcd dispatch_ functions, just as in ObjC. However, for aesthetic reasons, you can also pass your closure (block) after the close parentheses:
dispatch_async(dispatch_get_main_queue()) {
println("async hello world")
}

Best way using events in node.js

Which is the best approach for listening/launching events in node.js?
I've been testing event launching and listening in node.js by extending the model with EventEmitter and I'm wondering if it has sense this approach since the events are only listened when there is a instance of the model.
How can be achieved that events will be listened while the node app is alive??
Example for extending the model using eventEmitter.
// myModel.js
var util = require('util');
var events2 = require('events').EventEmitter;
var MyModel = function() {
events2.call(this);
// Create a event listener
this.on('myEvent', function(value) {
console.log('hi!');
});
};
MyModel.prototype.dummyFunction = function(params) {
// just a dummy function.
}
util.inherits(MyModel, events2);
module.exports = MyModel;
EDIT: A more clear question about this would be: how to keep a permanent process that listens the events during the app execution and it has a global scope (something like a running event manager that listens events produced in the app).
Would be a solution to require the file myModel.js in app.js? How this kind of things are solved in node.js?
I'm not entirely sure what you mean about events only being active when there is an instance of a model since without something to listen and react to them, events cannot occur.
Having said that, it is certainly reasonable to:
util.inherits(global,EventEmitter)
global.on('myEvent',function(){
/* do something useful */
});
which would allow you to:
global.emit('myEvent')
or even:
var ee=new EventEmitter();
ee.on('myEvent',...)
As for how to properly use EventEmitter: it's defined as
function EventEmitter() {}
which does not provide for initialization, so it should be sufficient to:
var Thing=function(){};
util.inherits(Thing,EventEmitter);
which will extend instances of Thing with:
setMaxListeners(num)
emit(type,...)
addListener(type,listener) -- aliased as on()
once(type,listener)
removeListener(type,listener)
removeAllListeners()
listeners(type)
The only possible "gotcha" is that EventEmitter adds its own _events object property to any extended object (this) which suggests you should not name any of your own object properties with the same name without unexpected behavior.

Resources