Reusing code between different event handlers

前端 未结 3 423
臣服心动
臣服心动 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 12:40

    define a function and do the job;

    var funCalled = function(){
        //your detailed actions
    }
    

    and call it in different conditions!

    if (some condition) {
        $(document).on('click','.selected-option',function(event){
            funCalled()
        })
    } else {
        $('.selected-option').click(function(event){
            funCalled()
        });
    }
    
    0 讨论(0)
  • 2021-01-26 12:48
    var testfunction = function(currentObj){
      // your code here
    }   
    
     if (some condition)
      {
          $(document).on('click','.selected-option',function(event){
              testfunction($(this));  
          });
      }
     else {
          $('.selected-option').click(function(event){
              testfunction($(this));  
           });
      }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题