I am trying to have my Node.js object cast events. Now this is not a problem if I make 'static' objects and instantiate them, but how do I do this when my object has no static grandpa, like when an object was created using object literal notation?
I am used to writing ExtJS syntax so I prefer everything in 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 does not have a constructor, because there don't need to be more instances.
Now how do I allow myObject
to emit events?
I have tried and tried to adapt code, but I cannot get it to work without rewriting my object to a form with a constructor like so:
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 // util.inherits(myClass, EventEmitter);
var myObject = new myClass; // Shouldn't be necessary for my single-instance case
Or adding my functions/prototypes to something constructed like so:
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 do I allow myObject
to emit events, while keeping the object literal notation?
So many confusing ways to do it, but not one within those JSON-like notated objects.
Why not use composition instead of inheritance?
var myObject = {
myFunction: function() {
console.log('foo');
},
urFunction: function() {
console.log('bar');
},
emitter: new EventEmitter()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With