简体   繁体   中英

Bind multiple events at the same time (JavaScript)

I haven't used eventlisteners for very long and now I'm trying to use multiple eventlisteners (or one eventlistener for multiple events) and bind at the same time. It isn't going that well. One thing I'm trying to do is having two buttons point to different methods (this.a and this.b, see below) in the same object. I want the buttons to belong to the same form element in the HTML code. How would I go about this?

This is a simplified version of the code:

HTML

<form id="form">
    <div ID="buttons">
        <button id="buttonA" type="submit">A</button>
        <button id="buttonB" type="submit">B</button>
    </div>
</form>

JS (doesn't work)

var Example = function() {
    //properties
}

Example.prototype.a = function() {
    document.querySelector("#buttonA").removeEventListener("submit", this.methodA);
    // do stuff
}

Example.prototype.b = function() {
    document.querySelector("#buttonB").removeEventListener("submit", this.methodB);
    // do stuff
}

Example.prototype.decision = function() {
    this.methodA = this.a.bind(this);
    this.methodB = this.b.bind(this);

    document.querySelector("#form").addEventListener("submit", function(event) {
    event.preventDefault();
    });

    document.querySelector("#buttonA").addEventListener("submit", this.methodA, false);
    document.querySelector("#buttonB").addEventListener("submit", this.methodB, false);
}

As you can see, the code is a mess right now. And even if it did work (which it doesn't), I'm not sure this is the best way to do it because I have to listen on the buttons separately (ideally, I think, you would only have to listen on #form).

What would be a proper and working solution?

Btw, method a and b are sort of like previous "states" in the program that the user can return to by clicking the buttons.

Handle click event on the form instead, and in that handle decide according to target property of the event which function to call next:

 var Example = function() { this.testA = "AAA"; this.testB = "BBB"; } Example.prototype.a = function() { alert(this.testA); } Example.prototype.b = function() { alert(this.testB); } var exam = new Example(); document.querySelector("#form").addEventListener("click", function(event) { event.preventDefault(); switch(event.target.id) { case "buttonA": exam.a.apply(exam); exam.a(); break; case "buttonB": exam.b.apply(exam); exam.b(); break; default: break; } }); 
 <form id="form"> <div ID="buttons"> <button id="buttonA" type="submit">A</button> <button id="buttonB" type="submit">B</button> </div> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM