Search code examples
javascriptbackbone.jsrequirejsbackbone-views

how to use window onunload event in backbone view


I am fairly new to backbone and I wanted to use window onunload event with one of my view. Actually I have created a view for my html page and I want to call some function at the unload of that page. This page is loaded inside a iframe or in a window.open and hence when the window is closed I want to call a function. But the event doesnt fire when I write

  events: {
          "beforeunload window": "myalert"
      }

or

$(window).on("beforeunload", myalert);

I saw some threads saying we should use route for this purpose but didn't got some good guide for it. Some suggestions/help will be appriciated.

Thank you.


Solution

  • One solution between numerous solution is to have your view listen to an event that your window will trigger, here's an example:

    In your view:

    Backbone.Events.once('windowClosed', myalert');
    window.open('your new window url here');
    

    And in the new window, when you want to close it:

    $(window).on("unload", function() {
        window.opener.Backbone.Events.trigger('windowClosed');
    });