티스토리 뷰
이벤트기반 비동기식 함수처리를 주로 하는 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 |
따라서 다음과 같이 호출을 하면 이런 결과가 나온다.
'거인의 어깨위에 서려는 > 서버 개발자를 위한' 카테고리의 다른 글
호스팅 서버에 ssh 로 git 연동하기 (0) | 2020.11.16 |
---|---|
[Firebase Functions] 서버리스를 이용한 간단한 Node.js 서버 배포 방법 (0) | 2020.03.08 |
[Let's Encrypt] HTTPS 인증서 무료로 발급받기 (2) | 2017.10.15 |
[Node.js] passport.js의 모든 것 (0) | 2016.06.05 |
[Node.js] passport-facebook 모듈 사용 관련 정보 (0) | 2016.05.30 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 소프트웨어 공학
- 구독료 계산기
- Android
- 좋은 습관이란
- patch-packages
- 최은영작가님
- 안드로이드
- release build issue
- git ssh 연동
- go
- 쉽게 말하는법
- 시간 관리
- MVP
- egghead
- 이미지 여백주기
- 애드 캣멀
- gradle
- git 실수
- 스크럼
- 이미지 일괄 변경
- 그리고 상상력
- node.js
- 아키텍처
- multiDex issue
- 공존이 필요해요
- 창의성을 지휘하라
- 소름돋는필력
- iterms
- retrofit
- React Native
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
글 보관함