0

I have a piece of JS code as follows:

window.onbeforeunload = function saveFav() {
//Some JS code
}

Now this same function needs to be called from a link click handler, so I am just directly calling the function as:

$("#someLink").click(function() {
   saveFav();
});

But for some reasons saveFav() is not getting called from link click. Is there some syntax issue OR will the function be called only on page unload?

I do not want to replicate the code as it is same on both unload and link click.

Please help me.

3
  • 1
    Although the function has a name, using a function expression won't generate a symbol for that name. Commented Sep 15, 2011 at 10:15
  • 1
    @Felix Right, the only purpose to giving a function name in a function expression is for recursion. Commented Sep 15, 2011 at 10:16
  • @Jacob: Exactly, the name is only accessible from inside the function. But named function expressions are not a good idea anyways due to bugs in IE (creating two instances of the same function). Commented Sep 15, 2011 at 10:20

3 Answers 3

7

Really simple, define the function once like so:

function saveFav() {
   //...
}

Then assign it to the appropriate handlers:

window.onbeforeunload = saveFav;
$("#someLink").click(saveFav);

The reasoning behind why your code does not work is because creating a named function expression does not create a symbol in the current scope with the function's name, rather the name only exists within the scope of the function itself, for the sole purpose of the function to have the ability to call itself recursively.

Sign up to request clarification or add additional context in comments.

Comments

2

You just want to define your function, and then assign it to both:

function saveFav() {
  //Some JS code
}

window.onbeforeunload = saveFav;
$("#somelink").click( saveFav );

You can of course assign either of these events to call an anonymous function which does some other stuff, and then calls saveFav, but it is not necessary to define an anonymous function that only calls saveFav.

Comments

0

You should define your saveFav function before assigning it to onbeforeunload if you want to call it in this way.

1 Comment

To be correct, the saveFav is the beforeunload event handler. It is not defined inside of it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.