Fitspade
Fitspade

Reputation: 439

How to declare the "beforeClose" event once time using CEP/JavaScript?

I need to know when the user decides to close the document he is on, so I found on various sites the "beforeClose" event.

I have 2 problems:

Here is how I currently do it in my jsx file :

main();

function main() {
    app.addEventListener("beforeClose", detectClose);
}

function detectClose() {
    alert('The document is closed'); 
}

Thank you in advance for your help !

Upvotes: 1

Views: 406

Answers (1)

Yuri Khristich
Yuri Khristich

Reputation: 14537

Not sure if understand how it's supposed to work, but I see two options. (1) You can check if there already are listener for the same event type and add the new listener only if there are no such listeners:

main();

function main() {
    if (if_not_exists('beforeClose')) app.addEventListener('beforeClose', detectClose);
}

function detectClose() {
    alert('The document is closed');
}

function if_not_exists(eventType) {
    var listeners = app.eventListeners;
    var i = listeners.length
    while (i--) if (listeners[i].eventType == eventType) return false;
    return true;
}

(2) Or you can remove all listeners (for given event type) beforehand with a function like this:

function remove_listeners(eventType) {
    var listeners = app.eventListeners;
    var i = listeners.length
    while (i--) if (listeners[i].eventType == eventType) listeners[i].remove();
}

Upvotes: 1

Related Questions