2014-05-13 5 views
1

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()); 
    }); 
+0

이벤트는 *'self'에서 방출됩니다. 즉, 인스턴스는 'timer.getTime' 멤버 함수가 아닙니다! 그것들은'getTime' 메쏘드 안에서 interval 콜백에 의해 방출됩니다. – Bergi

답변

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()); 
}); 
1

:

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

timer.getTime(); 

당신이 방법 내에서 이벤트를 방출하고 있지만, 방법과 사건 사이에 다른 관계는 없다. Clock 객체의 이벤트를 구독하고 clock 객체에서 이벤트를 방출합니다.

또한,이 나쁜, 지금까지이 작업을 수행하지 않습니다

Clock.prototype = EventEmitter.prototype; 

을 당신은 오히려이 작업을 수행 할 수 :

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

자신의 이벤트를 내보내는 여러 멤버 함수가있는 객체가있는 경우; 프로그래밍 스타일로서, 나는 그 함수를 호출 할 때 해당 함수가 내 보낸 이벤트에 대한 콜백을 바인드하는 것을 선호한다. – user3632523

+0

특정 메소드에 대한 이벤트에 대한 리스너를 정의 하시겠습니까? EventEmitter 객체는 그런 식으로 사용될 의도가 없으므로 질문에 답해야합니다. 나는 당신이 인생을 복잡하게 만들고 있다고 생각합니다. 그러나 어떤 경우 든 올바른 방향으로 당신을 밀어 넣을 수있는 몇 가지 코드가 있습니다 : https://gist.github.com/badsyntax/a8f498a2a0469ffadc39이 경로를 제안하지는 않습니다. 오히려보다 구체적인 이벤트 이름을 사용하십시오. – badsyntax

관련 문제