I've been practising the following structure:
class ProductService extends EventEmitter {
constructor() {
super()
}
getProductById(id) {
this.emit('beforeCall', { method: 'getProductById', params: { id }})
return new Promise((resolve, reject) => {
fetch(`/api/product/${id}`)
.then((res) => {
this.emit('complete', { method: 'getProductById', params: { id }})
resolve(res)
})
.catch((err) => {
this.emit('error', { method: 'getProductById', params: { id }})
reject(err)
})
})
}
}
Sample usage been:
const productService = new ProductService()
productService.on('beforeCall', (e) => {
if (e.method === 'getProductById') {
// getProductById method call detected!
if(e.params.id === 123) {
// getProductById(123) call detected!
}
}
})
productService.getProductById(123)
.then((res) => {
// product details fetched!
})
This is all good and promotes event driven architecture, however I hope the event listeners can be more elegant.
I've might have seen usages where event emitter is binded to method oppose to object, usage will looks something like this:
const productService = new ProductService()
productService.getProductById(123)
.on('beforeCall', (e) => {
// getProductById(123) call detected!
})
.then((res) => {
// product details fetched!
})
Is that possible?