Reusing code between different event handlers

前端 未结 3 414
臣服心动
臣服心动 2021-01-26 12:06

I have one code block which I want to invoke in different scenarios when a click is triggered, depending on whether the event is direct or is delegated.

But on changing

3条回答
  •  有刺的猬
    2021-01-26 13:07

    You don't have to use anonymous functions to handle events. Just write a regular function:

    function handleClick(event) {
      // lots of code
    }
    

    Then bind the function to as many events as you want:

    if (some condition) {
      $(document).on('click','.selected-option', handleClick);  
    else {
      $('.selected-option').click(handleClick);
    }
    

提交回复
热议问题