How to deal with javascript event handling in oops concept | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to deal with javascript event handling in oops concept

guys ! i was working with javascript objects . i cant found a solution to handle events in a systemic manner e.g to create multiple buttons then assign them events and handler function . i have assigned eventlistner method to the the object class .. the question is how to call this method in dom. .. i have searched in internet but not got the right answer ... i found it little bit confusing for me... any body please help me about how to assign events and handlers in oo js. i was dealing with className.prototype.addEventListner=function(event,handler){ } now i want to know how to call this method for perticular element made from this className

4th Nov 2018, 3:24 PM
Prakash
Prakash - avatar
2 Answers
5th Nov 2018, 12:03 AM
Calviղ
Calviղ - avatar
0
- Define an OOP class with event handling methods. - Instantiate objects from the class. - Use object methods to add event listeners. - Append objects to the DOM for interaction. Example: // Define an OOP class for buttons with event handling class ButtonWithEventHandler { constructor(text) { this.text = text; this.element = document.createElement('button'); this.element.textContent = text; } addClickListener(handler) { this.element.addEventListener('click', handler); } addToDOM(targetElement) { targetElement.appendChild(this.element); } } // Instantiate objects const button1 = new ButtonWithEventHandler('Button 1'); const button2 = new ButtonWithEventHandler('Button 2'); // Add event listeners button1.addClickListener(() => alert('Button 1 clicked!')); button2.addClickListener(() => alert('Button 2 clicked!')); // Append to the DOM const container = document.getElementById('button-container'); button1.addToDOM(container); button2.addToDOM(container);
29th Sep 2023, 12:19 PM
Chandan Kumar
Chandan Kumar - avatar