Event driven

here is an exciting way of designing a program that I am leaning towards to avoid (or use less of) using "setTimeouts) and rely more on triggered custom events.
I am using node js.

here is a basic example:

const EventEmitter = require('events')

class Game extends EventEmitter{
	constructor() {
		super();
		this.on('start', () => console.log("START"));
		this.on('over', () => console.log("GAME OVER!"));
		this.on('play', () => console.log("playing ..."))
	}
	start() {
		this.emit('start')
	}
	gameOver() {
		this.emit('over')
	}
	play() {
		this.emit('play')
	}
}

class Play {
	constructor() {		
		this.game = new Game()
	}
	playGame() {		
		this.game.start();
		this.game.play();
	}
	youLoose() {
		this.game.gameOver();
	}
}

const play = new Play();
setTimeout(play.youLoose.bind(play), 5000);
play.playGame();


output:
START
playing …
GAME OVER!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.