绑定成员函数发出的事件

js和EventEmitters。 我有下面的代码。 我想知道如何通过调用“getTime()”函数绑定“时间”事件。 像这样的东西:

timer.getTime.on("time", function() { console.log(new Date()); }); 

– 码 –

 var EventEmitter = require('events').EventEmitter; function Clock() { var self = this; this.getTime = function() { console.log("In getTime()"); setInterval(function() { self.emit('time'); console.log("Event Emitted!!"); }, 1000); }; } Clock.prototype = EventEmitter.prototype; Clock.prototype.constructor = Clock; Clock.uber = EventEmitter.prototype; var timer = new Clock(); timer.getTime.on("time", function() { console.log(new Date()); }); 

为什么不是这样的:

 timer.on("time", function() { console.log(new Date()); }); timer.getTime(); 

虽然你从一个方法中发出一个事件,但是方法和事件之间没有其他关系。 您订阅Clock对象上的事件,并在时钟对象上发出事件。

此外,这是不好的,永远不要这样做:

 Clock.prototype = EventEmitter.prototype; 

你想这样做:

 Clock.prototype = Object.create(EventEmitter.prototype); 

这是我可以实现的:

 var EventEmitter = require('events').EventEmitter; function Time(){ } function Clock() { } Time.prototype = Object.create(EventEmitter.prototype); Time.prototype.constructor = Time; Time.uber = EventEmitter.prototype; Clock.prototype.getTime = function() { var time = new Time(); var self = this; setInterval(function() { time.emit('time'); }, 1000); return time; }; var timer = new Clock(); timer.getTime().on("time", function() { console.log(new Date()); });