Created
April 6, 2011 02:53
-
-
Save jrockway/905042 to your computer and use it in GitHub Desktop.
class as event handler in node?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function EventListener() {} | |
EventListener.prototype.listen_to = function (that) { | |
for (var key in this) { | |
var event; | |
if(event = /^handle_(.+)$/.exec(key)){ | |
var method = [this, this[event[0]]]; | |
that.on( event[1], function() { | |
method[1].apply(method[0], arguments); | |
}); | |
} | |
} | |
}; | |
exports.EventListener = EventListener; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var EventEmitter = require('events').EventEmitter; | |
var EventListener = require('./events.js').EventListener; | |
function Emitter () {} | |
Emitter.prototype = new EventEmitter(); | |
function Listener () {} | |
Listener.prototype = new EventListener(); | |
Listener.prototype.handle_foo = function (arg) { | |
console.log('got foo ' + arg); | |
} | |
var emitter = new Emitter(); | |
var listener = new Listener(); | |
listener.state = 'test'; | |
listener.listen_to(emitter); | |
emitter.emit('foo', 'bar'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment