...

View Full Version : JavaScript objects - out of scope on onbeforeunload



toekneeh
01-13-2012, 11:42 PM
This is a bit of a strange one. I have been trying to call a function in a child object from the parent object but the child seems to be going out of scope in onbeforeunload function. These function calls work outside of a onbeforeunload, so it only fails when called in onbeforeunload. I can fix it by making the child object a global but I was trying to avoid that. Anyone know why my childobject is out of scope when called in onbeforeunload? Notice I call that same function in windows onload event and it works fine. Here is the code (I have simplified as much as possible to just show the error):


<html>

<head>
<title>Broken Page</title>

<script language="javascript" type="text/javascript">

var myparent;

function windowLaunch()
{
myparent = new parent();
myparent.getchildvalue();
window.onbeforeunload = myparent.getchildvalue;
}

function parent()
{
this.mychild = new childobject("myinput");
this.getchildvalue = function()
{
var tmpval = this.mychild.returnvalue();
};

}

function childobject(thename)
{
this.myprop = thename;
this.returnvalue = function()
{
return (document.getElementById(this.myprop).value);
};
}

</script>
</head>

<body id="thebody" onload="windowLaunch();">
<div id="outerdiv">
<span title="This Input Box">My Input:</span><br />
<input id="myinput" style="width: 290px"/>
</div>
</body>

</html>

DaveyErwin
01-14-2012, 12:17 AM
function windowLaunch()
{
myparent = new parent();
myparent.getchildvalue();
window.onbeforeunload = function(){myparent.getchildvalue()};
}

Dormilich
01-14-2012, 10:51 AM
I have been trying to call a function in a child object from the parent object but the child seems to be going out of scope in onbeforeunload function.
that’s because event handlers re-set the scope to the object the handler is attached to (in your case: window).

that’s the same for setTimeout(), setInterval() & addEventListener()

another option is using Function.bind() (where supported)

function windowLaunch()
{
myparent = new parent();
myparent.getchildvalue();
window.onbeforeunload = myparent.getchildvalue.bind(myparent);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum