Is it bad to have nested click handlers?

Someone mentioned this to me once, but I did not find any documentation to support the claim. Is it bad to have nested click handlers in an application? For example:

$("div").on("click", function(){
    //*Do things*
    $("p").on("click", function(){
        //*Do things*
    })
})

If this is bad practice, why, and what would be the best solution?

+4
source share
4 answers

Yes, it’s generally bad, maybe just what you want?

If someone double-clicks the div, an event handler for this paragraph is added twice, doing things twice, try

$('div').on('click', function() {
  $('p').on('click', function() {
    alert('This is annoyning');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>click me a few times ?</div>
<br /><br /><br />
<p>... then click me</p>
Run codeHide result

The best solution would be to simply not embed event handlers

var isClicked = false;

$('div').on('click', function() {
    isClicked = true;
});

$('p').on('click', function() {
    if (isClicked) // do stuff
});

(simplified to show the concept, do not use global variables, jQuery has data())

+3

, . div, , . , .

, , .

$("div").on("click", function(){
    //*Do things*
    $("p").off("click.myNameSpace").on("click.myNameSpace", function(){
        //*Do things*
    })
});

- , , .

(function () {
   var isActive = false;
    $("div").on("click", function(){
        isActive = false;
    });

    $("p").on("click", function(){
        if (isActive) {
            isActive = false;
            console.info("The p was clicked");
        }
    });
}());
+2

" ?": , , - GC. , , .

" ?": , , , (-)

I.E: b , a. : a, , , Handler b. b. b , .

0

, , "div", "p" . "divs", "p" , "p" .

One way around this is to use a delegate:

$(document).delegate("p", "click", function () { /* do stuff */ });

Another way is to untie existing handlers and then reformat them:

$("p").off(); $("p").on("click", function () { });

The third way is to use dirty flags (which should be set as global, which is not entirely accurate) to check if the handler for this call is working:

$("p").on("click", function () { if (flag) { return; } else { flag = true; doStuff(); flag = false; } });

0
source

Source: https://habr.com/ru/post/1621150/


All Articles