mlcheng / js-toast

A small JavaScript library that displays toast messages
MIT License
54 stars 19 forks source link

Updated main file #10

Open OblackatO opened 3 years ago

OblackatO commented 3 years ago

In my project I use a global variable to handle toasts. Basically, only one toast can exist at a time. So it is enough to have only one variable. When new toasts are created, something like the following happens:

var current_toast = ""
function item_ajoute_toast(item_name){
    const toast_options = {
        style: {
            main: {
                background: "green",
                color: "black",
            },
        },
        settings: {
            duration: 1500,
        },
    };
    if(current_toast !== null && current_toast !== "undefined" && current_toast !== ""){
        current_toast.hide()
    }
    current_toast = iqwerty.toast.toast(item_name+ ' ajouté!', toast_options);
}

Where current_toast, is the global variable. If current_toast is not undefined or null, then it exists and must be hidden so that next toast can be displayed. That is why there is the condition:

if(current_toast !== null && current_toast !== "undefined" && current_toast !== ""){
        current_toast.hide()
}

However, this causes a problem when the duration of the toast has faded. For instance, if the duration of some toast X is 2500, and if some other toast is displayed after that duration, hide() is called on a none existing object, and three errors occur. I provided patches for that in the exact places where those errors occur.

If a toast is displayed after X, but the duration of X is within 2500, that is fine. Basically, because X has not yet faded and the method hide() can safely be called.

I hope this explanation was clear :p