js 및 EventEmitters. 나는 아래의 코드를 가지고있다. 나는 "getTime()"함수를 호출 할 때 "time"이벤트를 어떻게 바인딩 할 수 있는지 알고 싶었다. 이 같은 뭔가 : 왜 그냥 이런구성원 함수에서 방출 된 이벤트 바인딩
timer.getTime.on("time", function() {
console.log(new Date());
});
--Code--
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());
});
이벤트는 *'self'에서 방출됩니다. 즉, 인스턴스는 'timer.getTime' 멤버 함수가 아닙니다! 그것들은'getTime' 메쏘드 안에서 interval 콜백에 의해 방출됩니다. – Bergi