The Observer Pattern: Observable Objects
Learn how to make objects observable and how to deal with memory leaks.
We'll cover the following...
Making any object observable
In the Node.js world, the EventEmitter
class is rarely used on its own. Instead, it’s more common to see it extended by other classes. In practice, this enables any class to inherit the capabilities of the EventEmitter
class, therefore becoming an observable object.
To demonstrate this pattern, let’s try to implement the functionality of the findRegex()
function in a class, as follows:
Press + to interact
import { EventEmitter } from 'events'import { readFile } from 'fs'class FindRegex extends EventEmitter {constructor (regex) {super()this.regex = regexthis.files = []}addFile (file) {this.files.push(file)return this}find () {for (const file of this.files) {readFile(file, 'utf8', (err, content) => {if (err) {return this.emit('error', err)}this.emit('fileread', file)const match = content.match(this.regex)if (match) {match.forEach(elem => this.emit('found', file, elem))}})}return this}}
The FindRegex
class that we just defined extends the EventEmitter
class to become a fully-fledged observable class. Always remember to use the super()
function in the constructor to initialize the EventEmitter
internals. ...