'How can I add event listener in node js
I'm trying to build a simple calculator where the operations will be done in a Node.js server. How can I add an event listener in the HTML page buttons so that when a button is clicked it does the calculation in the Node.js server?
Solution 1:[1]
The title is incorrect, as some users pointed out and you should throw some code snippets to showcase what you've been doing and where exactly your problem is. From the form of the question and details, I would suggest you do some research into the differences between frontend and backend and the solution will be clearer. But regarding your specific issue, assuming you're using Node, probably with Express and some templating engine;
- You'll want to attach a
onClicklistener to your button in yourejs/pug/hamlfile - Get the data from your
formin some way, either bygetElementByIdorFormData - Do a
fetchwithPOSTon the endpoint hitting your route -> controller with the data from your form or buttons res.json(...)or, more likelyres.render(...)your page with the related data result
Solution 2:[2]
Check out Node's EventEmitter. With this class, you can emit events and listen for them. You can also create your own classes which extend EventEmitter and make use of its functionality like so:
const { EventEmitter } = require('events');
class MyClass extends EventEmitter {
constructor() {
super();
}
doSomething() {
this.emit('someEvent');
}
}
const test = new MyClass();
test.on('someEvent', () => console.log('event was fired'));
test.doSomething();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manu |
| Solution 2 | mstephen19 |
