addEventListener custom event in JavaScript

Keywords: Javascript SDK IE JSON

addEventListener custom event in JavaScript

In js events, we first think of the common events such as click, dblclick, mouseover, mouseout, mouseenter, mouseleave, mousedown, mouseup, mousemove, wheel, context menu (when we click the right mouse button). Sometimes these predefined events can not meet our needs when we provide sdk for the third party.
Because the third-party sdk running environment is unknown, and it may lead to event conflicts, we need to customize events to avoid problems.
document.createEvent is used to create events. DOM Level 3 adds many event types. I think the most useful one is CustomEvent custom event.
To create a custom event for a DOM element:

1. Create event: var ev = document.createEvent('CustomEvent ');
2. Initialization event: ev.initCustomEvent('custom event name ', false (bubble allowed), false (interrupt allowed), args)
3. Add event listener for DOM: element.addEventListener('user defined event name ', fn,false)
4. Distribute (trigger) custom event: element.dispatchEvent(ev)

Custom event code example:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>TEST</title>
    <style>
    .send{
        margin: 10px 0;
        height: 50px;
        background: #6a61ff;
        color: #fff;
        line-height: 50px;
        text-align: center;
    }
     </style>
</head>
<body>
<div class="send" onclick="handleSend('1')">Click to trigger the custom event and pass parameter 1</div>
<div class="send" onclick="handleSend('2')">Click to trigger the custom event and pass parameter 2</div>
<div>
    <p>Receive custom event data</p>
    <p id="receive"></p>
</div>


<script>
    var event = document.createEvent('CustomEvent');
    // Initialize testEvent event event
    event.initEvent('testEvent', false, true);

    function handleSend(data){
        event.data = {
            data
        };
        // Trigger custom event
        window.dispatchEvent(event);
        console.log('1234')
    }

    window.addEventListener('testEvent', function(obj){
        console.log('receive',obj.data);
        document.getElementById('receive').innerHTML = JSON.stringify(obj.data)

    });

</script>
</body>
</html>


Posted by jack5100nv on Sun, 24 Nov 2019 07:56:54 -0800