JavaScript, stop additional event listeners

前端 未结 5 1564
盖世英雄少女心
盖世英雄少女心 2021-01-12 01:41

Imagine I have this code:

var myFunc1 = function(event) {
    alert(1);
}
var myFunc2 = function(event) {
    alert(2);
}

element.addEventListener(\'click\'         


        
5条回答
  •  执笔经年
    2021-01-12 02:10

    I'll start with the simplest answer that satisfies the constraints you've given so far. If it doesn't meet some condition you haven't yet specified, let me know and I'll update it.

    Only allow one click handler, and call functions based on conditions there. Your test code becomes:

    var myFunc1 = function(event) {
        alert(1);
    }
    var myFunc2 = function(event) {
        alert(2);
    }
    var clickHandler = function(event) {
        if (f1active) myFunc1(event);
        if (f2active) myFunc2(event);
    }
    
    element.addEventListener('click', clickHandler);
    var f1active = true;
    var f2active = true;
    

    and you can of course put any conditions you want to in clickHandler.

提交回复
热议问题