0

I want create an handler 'click' from a Javascript class and attach it to a simple button.

I created a simple Javascript class :

// from ./myclass.js
class Myclass
{
    constructor()
    {
        $("input.showAlert").bind("click", this._showAlert());
    }
    _showAlert(e){
        alert("foo");
    }
}

module.exports = {
    Myclass
};

And from my main js file :

// from ./main.js
const { Myclass } = require("./myclass");
var faa = new Myclass();

But if I do that, when I load my page via a browser, the alert "foo" appears automatically. I don't understand why and I don't want the alert is displaying automatically, but only when I click on the button 'input.addButton'.

My (very) simple html file :

<input class="showAlert" />

Where is my mistake ?

spacecodeur
  • 2,206
  • 7
  • 35
  • 71

2 Answers2

2

You shouldn't call your menthod here

$("input.showAlert").bind("click", this._showAlert());

Just pass the link to this method as:

$("input.showAlert").bind("click", this._showAlert);

Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
1

By writing this._showAlert() you immediately call the function, try this._showAlert

Guerric P
  • 30,447
  • 6
  • 48
  • 86