Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend object-literal objects for events in NodeJS?

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.

like image 519
Redsandro Avatar asked May 31 '12 16:05

Redsandro


1 Answers

Why not use composition instead of inheritance?

var myObject = {
  myFunction: function() {
    console.log('foo');
  },
  urFunction: function() {
    console.log('bar');
  },
  emitter: new EventEmitter()
}
like image 111
ziad-saab Avatar answered Oct 14 '22 18:10

ziad-saab