Domanda

What I'm trying to do is: when the user presses a cancel button, or navigates away of the page through a link or a menu option, I check if there are unsaved changes. If so, I ask the user if he/she wants to save. I can't do this with a javascript confirm window because I sometimes have more than two options, so I can't "hold" everything until the user makes a selection like confirm would. So I though to "save" the event, cancel it's current execution, whait until user makes up his/her mind, then take the action needed according to their answer, then raise back the original event. So, as a code example of what I thought: I have this piece of code:

var executingEvent;
function someFunction() {
    ...
    if(existUnsavedChanges) {
        showConfirmMessage();
        executingEvent = window.event;
        if (executingEvent.stopPropagation) { executingEvent.stopPropagation(); } else { executingEvent.cancelBubble = true; }
        ...
    }
}

Is there a way to later on do something like this?

raise (executingEvent);

Sounds a bit complex, I'd also welcome other options :)

È stato utile?

Soluzione

to fire an event use

elem.dispatchEvent(event)

Where elem is either the element you bound to or below it in the DOM (so it bubbles up).

Of course if you already stopped propagation the event wont bubble up, so you may want to create a new event object instead.

var ev = document.createEvent("Event");
ev.initEvent(type, true, true);
ev.origEv = originalEvent;
elem.dispatchEvent(ev);

Altri suggerimenti

It sounds to me like you're overthinking it - you could just raise the same type of event as the original event (which you would have cancelled) once the user has taken the action that you prompted for.

You can work out what the original event raised was by inspecting properties on the event object e.g. the type of event, the original target, etc.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top