简体   繁体   中英

Stop Event Propagation for a Specific Handler

tl;dr Summary

Write a function that—when registered to handle a specific event on multiple elements in a hierarchy—executes on the first element reached during bubbling but does not execute (or returns early) when bubbling further up the hierarchy. (Without actually stopping propagation of the event.)

Simple Example

Given this HTML

<!DOCTYPE html>
<body>
<div><button>click</button></div>
<script>
var d = document.querySelector('div'),
    b = document.querySelector('button');
d.addEventListener('mousedown',clickPick,false);
d.addEventListener('mousedown',startDrag,false);
b.addEventListener('mousedown',startDrag,false);
function clickPick(){ console.log('click',this.tagName); }
function startDrag(){ console.log('drag',this.tagName);  }
</script>

…clicking on the button yields this output:

drag BUTTON
click DIV
drag DIV

However, I don't want to drag the div. Specifically, I want startDrag to only be processed once, on the <button> , the leaf-most element for which it is registered in a particular propagation chain.

"Working" solution

The following JavaScript code has been tested to work on IE9, Chrome18, Firefox11, Safari5, and Opera11.

function startDrag(evt){
  if (seenHandler(evt,startDrag)) return;
  console.log('drag',this.tagName);
}

function seenHandler(evt,f){
  if (!evt.handlers) evt.handlers=[];
  for (var i=evt.handlers.length;i--;) if (evt.handlers[i]==f) return true;
  evt.handlers.push(f);
  return false;
}

The above does not work with IE8, even if you use the global window.event object; the same event object is not reused during bubbling.

The Question(s)

However, I'm not sure if the above is guaranteed to work…nor if it's as elegant as it could be.

  1. Is the same event object guaranteed to be passed up the chain during propagation?
  2. Is the event object guaranteed to never be re-used for different event dispatches?
  3. Is the event object guaranteed to support having an expando property added to it?
  4. Can you think of a more elegant way to detect if the same event handler function has been seen already on the current dispatch of an event?

Real World Application

Imagine this SVG hierarchy…

<g>
  <rect … />
  <rect … />
  <circle … />
</g>

…and a user who wants to be able to drag the whole group by dragging on any rect within it, and also to be able to drag just the circle by dragging on it.

Now mix in a generic dragging library that handles most of the details for you. I'm proposing to modify this library such that if the user adds a drag handler to both the <g> and the <circle> then dragging on the circle automatically prevents the dragging from initiating on the group, but without stopping propagation of all mousedown events (since the user might have a high level handler for other purposes that is desirable).

Here's a generic solution that works in the current versions of all major browsers...but not in IE8 and may not be guaranteed to work in future versions:

// Solution supporting arbitrary number of handlers
function seenFunction(evt,f){
  var s=evt.__seenFuncs;
  if (!s) s=evt.__seenFuncs=[];
  for (var i=s.length;i--;) if (s[i]===f) return true;
  evt.handlers.push(f);
  return false;
}

// Used like so:
function myHandler(evt){
  if (seenHandler(evt,myHandler)) return;
  // ...otherwise, run code normally
}

Alternatively, here is a less-generic solution that is slightly-but-probably-not-noticeably faster (again, not in IE8 and maybe not guaranteed to work in the future):

// Implemented per handler; small chance of error with a conflicting name
function myHandler(evt){
  if (evt.__ranMyHandler) return;
  // ...otherwise, run code normally
  evt.__ranMyHandler = true;
}

I will happily switch the acceptance to another answer with proper specs provided.

This looks good in Firefox, and can probably be adapted to non-standard browsers, since jQuery essentially does this with delegate and live . It uses stopPropagation and target , both of which are standard.

var d = document.querySelector('div'),
    b = document.querySelector('button');
d.addEventListener('mousedown',clickPick,false);
d.addEventListener('mousedown',startDrag,false);
function clickPick(evt){
    console.log('click', this.tagName);
}
function startDrag(evt){
    console.log('drag', evt.target.tagName);
    evt.stopPropagation();
}

For me, the order when you click on the button is reversed. Yours has "drag BUTTON" then "click DIV", while mine is the opposite. However, I think it's undefined in the original.

EDIT: Changed to use target . IE before 9 uses a non-standard srcElement property that means the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM