简体   繁体   中英

Add a custom property to an existing DOM event

Is it ok to add a custom property to an existing DOM event? I would like to "mark" click events in a leaf element (say, a <span> ) and catch the event (after bubbling) in an ancestor (say, <body> ) and take a decision based on that mark.

You can add a dataset item to the element called "data-xxx"

<span id="id" data-myvar="myvalue"></span>

And then later on

console.log( document.getElementbyID('id').dataset.myvar ) // myvalue

Sure you can add new properties to an event.

If I understand you correctly you are looking for a way to uniquely identify a specific event so you can de-dupe or count unique events or whatever.

For instance if you have one event handler handling some events on different elements and you want to make sure you handle each event only once. If an event bubbles you might handle the same event on multiple elements. Some events might bubble, some might not (eg because another handler called Event.stopPropogation() lower in the dom tree. Maybe you don't have that much control over where you attach your event handlers and have to rely on bubbling in some cases.

Example...

<div id="parent">
    <div id="child"></div>
</div>
var parentEl = document.querySelector('#parent'),
    childEl = document.querySelector('#child');

child.addEventListener('click', function (e) {
    var rand = ''+Math.floor(Math.random()*1000000);
    console.log('child', rand);
    e.custField = rand;
});
parent.addEventListener('click', function (e) {
    console.log('parent', e);
});
child.click();

Downside of this is that you are polluting someone else's objects that might be handled by code that isn't your own. Not usually a great idea.

Alternatively

1) Use Event.timeStamp

Your event handler can keep a cache of Event.timeStamp and use that to de-dupe handled events.


var eventHandler = (function () {
    var eventTimeStampCache = {};

    return function (evt) {
        if (evt.timeStamp in eventTimeStampCache) {
            console.log('Ignore this event.', evt);
            return;
        }
        eventTimeStampCache[evt.timeStamp] = true;
        console.log('Handle this event.', evt);
    };
})();

child.addEventListener('click', eventHandler);
parent.addEventListener('click', eventHandler);
child.click();

2) Use CustomEvent

If you are firing the events in the first place, use a CustomEvent that is all your own and feel free to make custom APIs and add event listeners that listed for your custom event.

I'd suggest firing a CustomEvent in response to the standard event except you have the same problem of knowing if this has been done already or not.

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