the little things
here's something I learnt the hard way a couple days ago and thought I'd better put it here so I don't forget it next time:
Javascript event handlers (eg. onclick) execute a whole block of javascript, not just necessarily 1 statement. This is easy to forget if all you are doing is calling a function (eg. verifyDelete()) and want to use the return value of the functions as return value of the event handler ( because if you give a event handler a return value of 'false' it won't execute the action it was called on - ie. a lcik on a link won't actually cause the browser to load that link).
Thus, this doesn't work:
<a href="delete" onclick="verifyDelete();"> Delete Me </a>
while this does:
<a href="delete" onclick="return verifyDelete();"> Delete Me </a>
Yes the return statement is important, since even though I'm doing just one function call in the onlcik handler definition, I could quite as easily have written 100 statements (seperated by semicolons) so without the return thres no way for the onlcik handler to know what the return value from my block of code is.
Javascript event handlers (eg. onclick) execute a whole block of javascript, not just necessarily 1 statement. This is easy to forget if all you are doing is calling a function (eg. verifyDelete()) and want to use the return value of the functions as return value of the event handler ( because if you give a event handler a return value of 'false' it won't execute the action it was called on - ie. a lcik on a link won't actually cause the browser to load that link).
Thus, this doesn't work:
<a href="delete" onclick="verifyDelete();"> Delete Me </a>
while this does:
<a href="delete" onclick="return verifyDelete();"> Delete Me </a>
Yes the return statement is important, since even though I'm doing just one function call in the onlcik handler definition, I could quite as easily have written 100 statements (seperated by semicolons) so without the return thres no way for the onlcik handler to know what the return value from my block of code is.
Labels: javascript

0 Comments:
Post a Comment
<< Home