简体   繁体   中英

how to: bind unbeforeunload call to window if function(param) is called?

a flash movie where users can draw is calling a JS Function. Whenever something is changed in the movie calls listenToUnload(true) . Whenever the save button in the Flashmovie is pressed listenToUnload(false); is called.

function listenToUnload(saved) {

   if (saved) {

      $(window).bind('unload', function() {
          closeWindowWarning;
      });

   } else if (!saved) {
       $(window).unbind('unload');
   }

}

function closeWindowWarning() { return "You haven't saved your last changes"; }

So, I actually wonder if this is the correct way to do this? Because listenToUnload(true) could be called multiple times in a row and I don't want to have the unload function bound multiple times to the window.

Is this the correct way of doing this? Any other approaches?

thank you

First, you need to bind on beforeunload , not unload .

You can store the flag (whether to confirm before unload) in a variable, or in $(document).data('confirm_unload', TRUE_OR_FALSE) and then:

function closeWindowWarning() { 
    if ($(document).data('confirm_unload'))
        return "You haven't saved your last changes"; 
}

And of course bind the beforeunload event once:

$(window).bind('beforeunload', closeWindowWarning)

You don't need to wrap closeWindowWarning in another function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM