Search code examples
javascriptbrowsercoffeescriptonbeforeunload

CoffeeScript onbeforeunload responding with function not string


I'm trying to prompt the use if they have any unsaved emails before they reload the current page. The unsaved emails are stored in a hash called unsaved. I wrote the the scripting in CoffeeScript.

If I use this code

  window.onbeforeunload = () ->
    return "Your emails are not saved.  Click \"Save Email\" on any email to save them all.  If you would like to discard your emails, just leave this page"  if unsaved.count > 0

Rather than prompting me with the message I get:

function ( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    }

Are you sure you want to reload this page?

The CoffeeScript is translated as:

window.onbeforeunload = function() {
  if (unsaved.count > 0) {
    return "Your emails are not saved.  Click \"Save Email\" on any email to save them all.  If you would like to discard your emails, just leave this page";
  }
};

How should I go about getting CoffeeScript to return the string rather than the function?


Solution

  • This is not really CoffeeScript related. The property window.onbeforeunload expects a string or void return value from your function, but if unsaved.count <= 0 you're returning something else:

    return $("form.edit_email_template").first().submit;
    

    Because the return value is non-void, it will attempt to cast the submit function into a string. To be honest I'm not sure why CoffeeScript generated that part, because it doesn't seem to appear in the original script.

    That said, you should return void if you don't want to see the dialog:

    if (unsaved.count > 0) {
        return 'your emails are not saved.';
    } else if (window.onbeforeunload) {
        $("form.edit_email_template").first().submit();
    }