Chartjs-JavaScript: Add Event Listener to an Event Listener

0👍

99% chance this doesn’t work so please someone kindly correct it so it works. Also I feel like this is not even on the right track.

function chartOnClickHandler(e) {
    return new Promise((res, rej)=>{
        if (e.native.detail !== 2) rej(0); // arbitrary reject value
        if (e.native.target.style.cursor === 'default') {
            res(handleDoubleClickAddPoint(e));
        }
        else if (e.native.target.style.cursor === 'grab'){
            res(handleDoubleClickRemovePoint(e));
        }
    })
}

function handleSynchronously(e) {
    chartOnClickHandler(e).then(
        // do synchronous stuff here
    );
}

0👍

I think I found a simple way around my issue. Instead of adding an event listener that waits for the function to finish, I found a way to mess around with the event queue. Using either queueMicrotask() or setTimeout(), I am able to add a function to the event queue that comes after the current running event.

Update: I ended up going with setTimeout(function, 1000) because I have to wait for the Chart’s animation to end to properly get the data I need.

function chartOnClickHandler(e) {
    if (e.native.detail !== 2) return;     // if not double click return
    if (e.native.target.style.cursor === 'default') {
        handleDoubleClickAddPoint(e);
    }
    else if (e.native.target.style.cursor === 'grab'){
        handleDoubleClickRemovePoint(e);
    }

    queueMicrotask( () => { 
        // Function to be run after the current task/event (chartOnClickHandler)
    });

    setTimeout( () => { 
        // Function to be run after the current task/event (chartOnClickHandler)
    }, 0);     // timeout can be 0, since we don't care about delay time, just to push the event down in the event queue.

} // Queued function will run here, after chartOnClickHandler has finished executing. 


// Below event handler is not needed and can be removed. 
chartElement.addEventListener('chartOnClickHandler', (e) => {
    // This event handler is not needed anymore
});

Leave a comment