Event and Watcher in JavaScript
In today’s programming, we need always need some of the sections of code that get emit automatically and perform the task completed without any interruption, and can handle all the scenarios which are defined.
So everyone has heard about events and watcher but how many of you know what’s the difference between them and where they can be used.
In simple words, we can call events are just like functions in a thread, just like functions they get executed when we call them. The event gets executed when they are triggered, and then they get executed in a thread.
Whereas What is a Watcher?
A watcher is a special Vue. js feature that allows you to spy on one property of the component state, and run a function when that property value changes.
Or in simple words, Watchers are using to keep watch on any particular pre-recorded data like a database. A watch is like a watchman he keeps his eye on any update or change and whenever that happens, he calls for a handler where the change is handled.
After a call to definition, let’s see how it looks and works before installing it through npm, follow the above doc for the same!
This is how an event definition looks like …
@OnEvent(NAME_OF_EVENT, { async: true }) async handle(PARAMETER: DATA_TYPE) { try { // something.... which does it work } catch (e) { // catch the error and log }}
And now let see how we can trigger an event…
1. First we need to import event emitter.
2. Using event emitter — emit the event we want to trigger and pass the parameter if any.
this.EventEmitter.emit(NAME_OF_EVENT, PARAMETER_TO_PASSED);
Now let’s have our attention on Watcher, it usually keeps eye on change/update in the database as define.
private updateTestListener() { let filter = { $match: { $and: [{<QUERY>}, { $or: [{ operationType: "update" }] } ] } };this.<Schema_Model>.watch([filter], { fullDocument: "updateLookup" }).on("change", async doc => this.handleUpdates(doc));}async handleUpdates(doc) { const { operationType, fullDocument: {<PARTICULAR_FIELD>} } = doc; // this function does what it suppose to do on fields which is got updated... // we can even collect the only updated item on which we need to perform something.}
Both are injectable functionality that can be used in any module and class after mentioning them in Provider (Look at Nest Js doc for more).
Conclusion
We looked into the javascript event and watcher and found a lot of information that helped us figure out what was going on. This article is merely a summary of ideas that you can explore more in the never-ending world.