1

I want to create class and want to pass my element to it and fire events form class instead of triggering from javascript events everytime.

My try

HTML :

<div id="upload-container">
<label for="myfile">Select a file:</label>
<input type="file" id="fileInput" name="myfile">
<button id="send"> Upload </button> </div>

Javascript class :

function Myevents(ele) {
    this.element = ele;
}

Myevents.prototype = {

    init: function() {
        this.element.addEventListener('click', function(file) {
            console.log(file)
        }(this.element));

        this.element.addEventListener('mouseover', function(file) {
            console.log(file)
        }(this.element));
    }
}

var ele = document.getElementById('send');
var instance = new Myevents(ele);
instance.init();

instance.click() ;  // should be able to call it manually
instance.mouseover();   // should be able to call it manually

here both above two calls are not firing as required, how to handle this ,any help would appreciated.

jsduniya
  • 2,464
  • 7
  • 30
  • 45

1 Answers1

1

Here I recreate your Myevents function. I make a click function as a prototype and attach click event listener and call it implicitly.

const Myevents = function(el) {
 this.element = el;
}

Myevents.prototype = {
 click: function() {
     // Attach the event listener
     this.element.addEventListener('click', (e) => {
         e.preventDefault();
            console.log('clicked');
        });
        
        // Finally fire the click
        // this.element.click();
    }
}

const el = document.querySelector('#clickbtn');
const instance = new Myevents(el);
instance.click();
<div>
  <p>Hello World</p>
  <button id="clickbtn">Ok</button>
</div>

Note: I don't know but let me know if it fulfills your requirement.

Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30