반응형

기존 전역 객체 process 가 아닌 모듈로 만들어 이벤트를 호출 할 수있는 즉 객체에 EventEmitter를

상속 받아 이벤트를 호출하는 구조


util 모듈을 통해 상속구문을 보다 간편하게 처리할 수 있다


//calculation는 EventEmitter을 상속 받는다
util.inherits(calculation, EventEmitter);



'stop' 인 사용자 정의형 이벤트를 calculation 에 등록함


calculation.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
 
var EventEmitter = require('events').EventEmitter;      //이벤트를 위한 모듈
var util = require('util');                             //프로포타입 객체를 쉽게 상속 할 수 있게 해줌
 
 
var calculation = function () {
 
    this.on('stop'function ()
        {
        console.log('calculation 에 stop 이벤트 전달됨');
        }
    );
 
};
 
calculation.prototype.add = function (a, b) {
    return a + b;
}
 
//calculation는 EventEmitter을 상속 받는다
util.inherits(calculation, EventEmitter);
 
 
 
module.exports = calculation;
 
 




1
2
3
4
5
6
7
var calc = require('./calculation');
 
//모듈로 읽어온 것을 객체로 만들 수 있음 moudle.exports 느 calculation 과 동일한 형태임으로
var calculationReal = new calc();
 
calculationReal.emit('stop');
 





결과




반응형

+ Recent posts