티스토리 뷰

이벤트기반 비동기식 함수처리를 주로 하는 Node.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
var events = require('events'); // Event 라이브러리 가져오기
 
function Calories() {
    this.calories = 0;
    this.bmr = 2000;
    events.EventEmitter.call(this); //Event 정의
    this.eat = function(amount) {
        this.calories += amount;
        this.emit('caloriesChanged');
    };
 
    this.exercise = function(amount, kind) {
        this.calories -= amount;
        this.emit('caloriesChanged');
        this.emit('exercised',kind);
    };
 
    this.todayCalories = function(){
        this.emit('todayEnd');
    }
}
//클래스 프로토타입으로 이벤트 프로토타입을 가져옴
Calories.prototype.__proto__ = events.EventEmitter.prototype
 
cs


현재 Calories라는 클래스를 선언하고 있는데, 이 클래스에 이벤트를 정의하기 위해서는 

6번째 줄과 같이 이벤트 라이브러리에서 위임을 받아야한다. 

그 후 이벤트의 기본 함수를 가져오기 위해 23번줄에서 클랙스 프로토타입을 이벤트의 프로토타입으로 선언한다.

이 과정이 끝나면 이 클래스는 이벤트를 적용하고 사용할 수 있다.

이미 클래스 안의 메소드에서는 this.emit함수로 이벤들을 호출하고 있는데

음식을 먹거나 운동을 하면 caloriesChanged 이벤트를 

운동하면 exercised 이벤트를 

그리고 오늘 칼로리를 확인하면 todayEnd 이벤트를 호출하게 된다.

1
2
3
4
5
6
7
8
9
10
11
var calories = new Calories();
calories.on("caloriesChanged", displayCalories);
calories.on("exercised"function(kind){
    displayExercise(kind);
});
calories.on("todayEnd"function(){
    checkCalories(this);
});
calories.on("todayEnd"function() {
    checkGoal(this, 1500);
});
cs


여기서는 클래스에서 이벤트 발생시 행동을 정의하고 있다.

첫번째 이벤트 발생시 미리 정의된 displayCalories라는 함수를 호출하고,

두 번째는 kind라는 인수를 이벤트로부터 받아서 역시 미리 정의된 displayExcercise라는 함수에 넘겨준다.

마지막 이벤트는 넘겨주는 인수는 없고 두 가지 함수를 실행한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function displayCalories(){
    console.log("Current Calories: %d kcal", this.calories);
}
function displayExercise(kind){
    console.log("%s is Fun Fun Exercise!! ", kind);
}
 
function checkCalories(kcal){
    if(kcal.calories > kcal.bmr){
        console.log("You got extra %d kcal.", kcal.calories - kcal.bmr);
    }else if(kcal.calories < kcal.bmr){
        console.log("You lost %d kcal in your body.", kcal.bmr - kcal.calories);
    }else{
        console.log("You used exactly same kcal with your bmr!");
    }
}
 
function checkGoal(kcal, goal){
    if (kcal.calories < kcal.bmr){
        console.log("Goal Achieved!!");
    }
}
cs


각 함수는 이름과 같이 현재 칼로리와 운동 종류, 클래스 안에 정의된 BMR값과 비교하여 콘솔창에 보여주고, 

목적을 달성했는지 여부를 판단한다.

보는 것과 같이 이벤트 작동시 함수에 this를 인수로 넣어주면 Calories 객체 자신이 들어가서 객체 변수인 calories, bmr 값에 접근할 수 있는 것을 알 수 있다.

1
2
3
4
5
6
7
calories.eat(600);
calories.eat(700);
calories.eat(800);
calories.todayCalories();
calories.exercise(300"Running");
calories.todayCalories();
 
cs


따라서 다음과 같이 호출을 하면 이런 결과가 나온다.



댓글