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());
});
答案 0 :(得分:1)
为什么不这样:
timer.on("time", function() {
console.log(new Date());
});
timer.getTime();
虽然您从方法中发出事件,但方法和事件之间没有其他关系。您订阅Clock对象上的事件,然后在clock对象上发出事件。
此外,这很糟糕,不要这样做:
Clock.prototype = EventEmitter.prototype;
你想这样做:
Clock.prototype = Object.create(EventEmitter.prototype);
答案 1 :(得分:0)
这就是我实现它的方式:
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());
});