I see this pattern in quite a few Node.js libraries:
Master.prototype.__proto__ = EventEmitter.prototype;
(source here)
Can someone please explain to me with an example, why this is such a common pattern and when it's handy?
As the comment above that code says, it will make Master inherit from EventEmitter.prototype, so you can use instances of that 'class' to emit and listen to events.
For example you could now do:
masterInstance = new Master();
masterInstance.on('an_event', function () {
console.log('an event has happened');
});
// trigger the event
masterInstance.emit('an_event');
Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':
var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);
2nd Update: with ES6 classes upon us, it is recommended to extend the EventEmitter class now:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
See https://nodejs.org/api/events.html#events_events
ES6 Style Class Inheritance
The Node docs now recommend using class inheritence to make your own event emitter:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {
// Add any custom methods here
}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
Note: If you define a constructor() function in MyEmitter, you should call super() from it to ensure the parent class's constructor is called too, unless you have a good reason not to.
To inherit from another Javascript object, Node.js's EventEmitter in particular but really any object in general, you need to do two things:
provide a constructor for your object, which completely initializes the object; in the case that you're inheriting from some other object, you probably want to delegate some of this initialization work to the super constructor.
provide a prototype object that will be used as the [[proto]] for objects created from your constructor; in the case that you're inheriting from some other object, you probably want to use an instance of the other object as your prototype.
This is more complicated in Javascript than it might seem in other languages because
Javascript separates object behavior into "constructor" and "prototype". These concepts are meant to be used together, but can be used separately.
Javascript is a very malleable language and people use it differently and there is no single true definition of what "inheritance" means.
In many cases, you can get away with doing a subset of what's correct, and you'll find tons of examples to follow (including some other answers to this SO question) that seem to work fine for your case.
For the specific case of Node.js's EventEmitter, here's what works:
var EventEmitter = require('events').EventEmitter;
var util = require('util');
// Define the constructor for your derived "class"
function Master(arg1, arg2) {
// call the super constructor to initialize `this`
EventEmitter.call(this);
// your own initialization of `this` follows here
};
// Declare that your class should use EventEmitter as its prototype.
// This is roughly equivalent to: Master.prototype = Object.create(EventEmitter.prototype)
util.inherits(Master, EventEmitter);
Possible foibles:
If you use set the prototype for your subclass (Master.prototype), with or without using util.inherits, but don't call the super constructor (EventEmitter) for instances of your class, they won't be properly initialized.
If you call the super constructor but don't set the prototype, EventEmitter methods won't work on your object
You might try to use an initialized instance of the superclass (new EventEmitter) as Master.prototype instead of having the subclass constructor Master call the super constructor EventEmitter; depending on the behavior of the superclass constructor that might seem like it's working fine for a while, but is not the same thing (and won't work for EventEmitter).
You might try to use the super prototype directly (Master.prototype = EventEmitter.prototype) instead of adding an additional layer of object via Object.create; this might seem like it's working fine until someone monkeypatches your object Master and has inadvertently also monkeypatched EventEmitter and all its other descendants. Each "class" should have its own prototype.
Again: to inherit from EventEmitter (or really any existing object "class"), you want to define a constructor that chains to the super constructor and provides a prototype that is derived from the super prototype.
This is how prototypical (prototypal?) inheritance is done in JavaScript.
From MDN:
Refers to the prototype of the object, which may be an object or null
(which usually means the object is Object.prototype, which has no
prototype). It is sometimes used to implement prototype-inheritance
based property lookup.
This works as well:
var Emitter = function(obj) {
this.obj = obj;
}
// DON'T Emitter.prototype = new require('events').EventEmitter();
Emitter.prototype = Object.create(require('events').EventEmitter.prototype);
Understanding JavaScript OOP is one of the best articles I read lately on OOP in ECMAScript 5.
I thought this approach from http://www.bennadel.com/blog/2187-Extending-EventEmitter-To-Create-An-Evented-Cache-In-Node-js.htm was pretty neat:
function EventedObject(){
// Super constructor
EventEmitter.call( this );
return( this );
}
Douglas Crockford has some interesting inheritence patterns too: http://www.crockford.com/javascript/inheritance.html
I find inheritence is less often needed in JavaScript and Node.js. But in writing an app where inheritence might affect scalability, I would consider performance weighed against maintainability. Otherwise, I would only base my decision on which patterns lead to better overall designs, are more maintainable, and less error-prone.
Test different patterns out in jsPerf, using Google Chrome (V8) to get a rough comparison. V8 is the JavaScript engine used by both Node.js and Chrome.
Here're some jsPerfs to get you started:
http://jsperf.com/prototypes-vs-functions/4
http://jsperf.com/inheritance-proto-vs-object-create
http://jsperf.com/inheritance-perf
To add to wprl's response. He missed the "prototype" part:
function EventedObject(){
// Super constructor
EventEmitter.call(this);
return this;
}
EventObject.prototype = new EventEmitter(); //<-- you're missing this part
Related
Here is the doc I am confused with.
When using pre-ES6 style constructors
const { Transform } = require('stream');
const util = require('util');
function MyTransform(options) {
if (!(this instanceof MyTransform))
return new MyTransform(options);
Transform.call(this, options);
}
util.inherits(MyTransform, Transform);
Why do we need to check this instanceof MyTransform? As far as I know, as long as we invoke new MyTransform(), evaluation of this instanceof MyTransfrom will always return true. Maybe using MyTransform() to create a Transform instance can be found in many code bases? This is the only reason I could guess.
What is the purpose of util.inherits(MyTransform, Transform); ? Just to ensure that new MyTransform() instanceof Transform returns true?
Thank you for your time in advance!
MyTransform is just a function like any other function. There's nothing special about it, and so calling it as a function (without new) will work perfectly fine. So what should happen in that case? According to this code: fall through to a constructor call and returning the resulting instance object.
As per the documentation for that function it enforces prototype inheritance, because again, you wrote MyTransform as just a plain function: while you can use new with any function, you didn't write any of the code necessary for proper prototype inheritance so using new will give you a completely useless object. That means either you add the code necessary to set set up prototype inheritance yourself, or you ask a utility function to do that for you.
I am a newbie to patterns and was wondering whether it is possible to implement observer pattern using REST api. My current view is that it is not possible since REST is more of a pull architecture while observer is more of a push architecture.
Your thoughts are welcome.
An object maintains a list of dependents/observers and notifies them automatically on state changes. To implement the observer pattern, EventEmitter comes to the rescue
// MyFancyObservable.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function MyFancyObservable() {
EventEmitter.call(this);
}
util.inherits(MyFancyObservable, EventEmitter);
This is it; we just made an observable object! To make it useful, let's add some functionality to it.
MyFancyObservable.prototype.hello = function (name) {
this.emit('hello', name);
};
Great, now our observable can emit event - let's try it out!
var MyFancyObservable = require('MyFancyObservable');
var observable = new MyFancyObservable();
observable.on('hello', function (name) {
console.log(name);
});
observable.hello('john');
for more details follow the link
Fundamental Node.js Design Patterns
Immediate State Updates for REST/HTTP APIs using Observer Pattern
I am new to Node.js and started learning it.
I came across "EventEmitter" in "events" module in node.
After following the example in EventEmitter documentation I wrote the bolow code,
var EventEmitter = require("events");
var util = require("util");
var Ticker = function(){
var self = this;
EventEmitter.call(self);
self.start = function(){
setInterval(function(){
self.emit("tick");
},1000);
}
self.on("tick",function(){
console.log("Keep Ticking");
});
}
util.inherits(Ticker,EventEmitter);
var ticker = new Ticker();
ticker.start();
When I run the code
node example03.js
the output is
rahul#ubuntu:~/rahul/NodePractise/EventEmitter$ node example03.js
Keep Ticking
Keep Ticking
Keep Ticking
Keep Ticking
^C
rahul#ubuntu:~/rahul/NodePractise/EventEmitter$
Now even if I comment the line
//EventEmitter.call(self);
The code works fine.
So whats the purpose of the above line and how is its presence important.
So whats the purpose of the above line and how is its presence
important.
The line of code:
EventEmitter.call(self);
is so the base class (what you inherited from) can properly initialize it's own instance each time you create a new instance of your derived class. This is a very important step that should not be left out.
To explain exactly what it is doing, EventEmitter is the constructor function of the object you derived from. .call(self) is telling Javascript to call that constructor function and to set the this value to the object that was just created (which is pointed to by self in your code). That will end up calling the EventEmitter constructor in the same way as new EventEmitter() would call it which is what you want. The only difference here from new EventEmitter() is that you're pointing this at an instance of your derived object, not at just an EventEmitter object.
In all cases of inheritance, you should call the base class constructor so it can properly initialize itself. But, there may be some types of objects that don't really do much in the constructor so things may happen to work if you leave it out. Or they may just seem to work, but there will be problems down the road.
Adding or removing EventEmitter.call(this) in my Node example doesn't
make any difference, why?
If you look at the EventEmitter code on Github, you can see that the EventEmitter constructor does this:
function EventEmitter() {
EventEmitter.init.call(this);
}
And, the .init() method does this:
EventEmitter.init = function() {
this.domain = null;
if (EventEmitter.usingDomains) {
// if there is an active domain, then attach to it.
domain = domain || require('domain');
if (domain.active && !(this instanceof domain.Domain)) {
this.domain = domain.active;
}
}
if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
this._events = {};
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
So, if you fail to call the parent constructor, there will be several instance variables in the EventEmitter object that are not properly initialized. What this does to the code is anyone's guess (it would take further code study and testing to know for sure), but it is not a good thing. Some features might work without this initialization, but it is very likely that other things will not work properly.
Is there a best-practice solution to be able to use within in promise this? In jQuery i can bind my object to use it in my promise/callback - but in angularJS? Are there best-practice solutions? The way "var service = this;" i don't prefer ...
app.service('exampleService', ['Restangular', function(Restangular) {
this._myVariable = null;
this.myFunction = function() {
Restangular.one('me').get().then(function(response) {
this._myVariable = true; // undefined
});
}
}];
Are there solutions for this issue? How i can gain access to members or methods from my service within the promise?
Thank you in advance.
The generic issue of dynamic this in a callback is explained in this answer which is very good - I'm not going to repeat what Felix said. I'm going to discuss promise specific solutions instead:
Promises are specified under the Promises/A+ specification which allows promise libraries to consume eachother's promises seamlessly. Angular $q promises honor that specification and therefor and Angular promise must by definition execute the .then callbacks as functions - that is without setting this. In strict mode doing promise.then(fn) will always evaluate this to undefined inside fn (and to window in non-strict mode).
The reasoning is that ES6 is across the corner and solves these problems more elegantly.
So, what are your options?
Some promise libraries provide a .bind method (Bluebird for example), you can use these promises inside Angular and swap out $q.
ES6, CoffeeScript, TypeScript and AtScript all include a => operator which binds this.
You can use the ES5 solution using .bind
You can use one of the hacks in the aforementioned answer by Felix.
Here are these examples:
Adding bind - aka Promise#bind
Assuming you've followed the above question and answer you should be able to do:
Restangular.one('me').get().bind(this).then(function(response) {
this._myVariable = true; // this is correct
});
Using an arrow function
Restangular.one('me').get().then(response => {
this._myVariable = true; // this is correct
});
Using .bind
Restangular.one('me').get().then(function(response) {
this._myVariable = true; // this is correct
}.bind(this));
Using a pre ES5 'hack'
var that = this;
Restangular.one('me').get().then(function(response) {
that._myVariable = true; // this is correct
});
Of course, there is a bigger issue
Your current design does not contain any way to _know when _myVariable is available. You'd have to poll it or rely on internal state ordering. I believe you can do better and have a design where you always execute code when the variable is available:
app.service('exampleService', ['Restangular', function(Restangular) {
this._myVariable =Restangular.one('me');
}];
Then you can use _myVariable via this._myVariable.then(function(value){. This might seem tedious but if you use $q.all you can easily do this with several values and this is completely safe in terms of synchronization of state.
If you want to lazy load it and not call it the first time (that is, only when myFunction is called) - I totally get that. You can use a getter and do:
app.service('exampleService', ['Restangular', function(Restangular) {
this.__hidden = null;
Object.defineProperty(this,"_myVariable", {
get: function(){
return this.__hidden || (this.__hidden = Restangular.one('me'));
}
});
}];
Now, it will be lazy loaded only when you access it for the first time.
I find that everything I read about EventEmitter (books or internet) uses the inheritance implementation.
Beyond being more convoluted (using Util.inherits, calling the EventEmitter constructor inside the class), you get problems with multiple inheritance (unless you add more convolution) and less flexibility on class-wide events I find.
What's wrong with this picture?:
EventEmitter = require('events').EventEmitter;
function DummyContainer()
{
this.Events = new EventEmitter();
}
DummyContainer.prototype.ClassEvents = new EventEmitter();
Test1 = new DummyContainer();
Test1.Events.on('Test', function() {
console.log('Test');
});
Test1.ClassEvents.on('ClassTest', function() {
console.log('ClassTest');
});
Test2 = new DummyContainer();
Test1.Events.emit('Test');
Test2.ClassEvents.emit('ClassTest');
It seems to me that the above is a little more readable, doesn't need any workaround for multiple inheritance (because it doesn't use inheritance in the first place) and as a bonus, allows you to easily make a distinction between classwide and instance events.
Beyond having to type a little more if you don't use it, is there any incentive to use the inheritance way instead of this?