I am trying to create a Node.js translation event object. Now this is not a problem if I create βstaticβ objects and create an instance of them, but how to do this when my object does not have a static grandfather, for example, when the object was created using the object literal symbol?
I use ExtJS to write the syntax, so I prefer everything in the object literal.
// var EventEmitter = require('events').EventEmitter; // How where when? myObject = { myFunction: function() { console.log('foo'); }, urFunction: function() { console.log('bar'); } };
This is an object. It has no constructor because no more instances are needed.
Now, how can I let myObject emit events?
I tried and tried to adapt the code, but I can't get it to work without rewriting my object into a form with a constructor like this:
var EventEmitter = require('events').EventEmitter; var util = require('util'); function myClass() { EventEmitter.call(this); myFunction: function() { this.emit('foo'); }, urFunction: function() { this.emit('bar'); } }; myClass.prototype = Object.create(EventEmitter.prototype);
Or adding my functions / prototypes to those constructed as follows:
var EventEmitter = require('events').EventEmitter; var util = require('util'); var myObject = new EventEmitter(); // or // var myObject = Object.create(new EventEmitter); // Dunno difference myObject.myFunction = function() { this.emit('foo'); }, myObject.urFunction = function() { this.emit('bar'); } }; util.inherits(myObject, EventEmitter);
How to allow myObject emit events while maintaining object literal notation? There are so many confusing ways to do this, but not one of those JSON-like note objects.
Redsandro
source share