I'm trying to build a simple calculator where the operations will be done in a nodejs 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
CodePudding user response:
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
onClick
listener to your button in yourejs
/pug
/haml
file - Get the data from your
form
in some way, either bygetElementById
orFormData
- Do a
fetch
withPOST
on 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
CodePudding user response:
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();