on and off problems in jQuery

Keywords: JQuery

First of all, the basic scientific knowledge. On () and. Off () method is the jQuery 1.7 official release

Code example 1

   var $test = $(document);

function handler1() {
  console.log( "handler1" );
  $test.off( "click", handler2 );
}

function handler2() {
  console.log( "handler2" );
}

$test.on( "click", handler1 );
$test.on( "click", handler2 );

The first time you click document, you will see

handler1
handler2

Code example 2

var $test = $(document);

function handler1() {
  console.log( "handler1" );
  $test.off( "mouseup", handler2 );
}

function handler2() {
  console.log( "handler2" );
}

$test.on( "mousedown", handler1 );
$test.on( "mouseup", handler2 );

The first time you click document, you will see

handler1

The question is, why is the addition or deletion of the same event invalid in the current process?

Check Jq source code:

//Get the array of triggered events. When click ing is triggered in the above code, there are two values in the array, while when mousedown is triggered, there is only one value. This value is an internally encapsulated handleObj object
handlers = ((jQuery._data(this, "events") || {})[event.type] || [])

...

//After that, the handlers array will be sliced according to whether it is delegated or not (it is also the place where the handlers are copied, which makes the off in click invalid when clicking for the first time), and then added to the array handlerQueue
handlerQueue.push({ elem: this, matches: handlers.slice(delegateCount) })

...
//The last trigger is to traverse the matches in the handlerQueue to execute
 for (i = 0; i < handlerQueue.length && !event.isPropagationStopped() ; i++) {
                matched = handlerQueue[i];
                event.currentTarget = matched.elem;

                for (j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped() ; j++) {
                    ...
                    }
}

The reason is that when events are encapsulated in jq, events of the same type will be added to the same array. When events are triggered, traversal is a copy of the array. Off does not change the copied array. Therefore, when click ing for the first time, hanner2 is output. For mousedown and mouseup, events of different types are encapsulated into two arrays , so it is effective to turn off mouseup in mousedown.

Posted by matfish on Sat, 04 Apr 2020 08:37:06 -0700