HTA Javascript - why is object out of scope in onbeforeunload? - javascript

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 it 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:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Broken HTA</title>
<HTA:APPLICATION
ID="Broken HTA"
APPLICATIONNAME="Broken HTA"
BORDERSTYLE = "flat"
CAPTION="Yes"
CONTEXTMENU = "no"
INNERBORDER = "no"
MAXIMIZEBUTTON = "no"
MINIMIZEBUTTON = "yes"
NAVIGABLE = "No"
SCROLL = "auto"
SCROLL FLAT = "Yes"
SELECTION="no"
SYSMENU="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
VERSION = "1.0"
BORDER="thick"
>
<script language="javascript" type="text/javascript">
var myparent;
function windowLaunch()
{
myparent = new parent();
myparent.getchildvalue();
window.onbeforeunload = myparent.getchildvalue;
window.resizeTo(500, 610);
}
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>

this is based on how a function is called. Calling myparent.getchildvalue() is fine, but as soon as you assign myparent.getchildvalue as a handler, it will be called out of context. You can demonstrate this simply:
var obj = { val: 42, fn: function(){ alert(this.val) } };
ref = obj.fn;
alert(obj.fn === ref); // true, so expect the following to do the same thing...
obj.fn(); // 42, so far so good
ref(); // undefined. uh oh...
You can get around this by wrapping:
...
window.onbeforeunload = function(){ myparent.getchildvalue(); };
...
or binding:
...
window.onbeforeunload = myparent.getchildvalue.bind(myparent);
...

Related

How can I send a statement to be used as a command within code?

What I've been trying to do is to pass a statement like oninput or onmouseover and then use them as actual statements in a method.
function Controller() {
this.listen = function(elem, func, statement) {
elem.statement = function() {//and then use it here
func(elem);
};
return true;
};
}
var age = document.getElementById('age');
var controller = new Controller();
controller.listen(age, callMe, oninput);//set the statement here
function callMe(elem) {
console.log('hey');
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<input type="number" id="age" />
</body>
</html>
Is there a way to do this?
Pass the oninput as a string ("oninput") and then use square brackets to access the property of elem:
function Controller() {
this.listen = function(elem, func, statement) {
elem[statement] = function() {//and then use it here
func(elem);
};
return true;
};
}
var age = document.getElementById('age');
var controller = new Controller();
controller.listen(age, callMe, "oninput");//set the statement here
function callMe(elem) {
console.log('hey');
}
However, I recommend you using element.addEventListener() instead of .onevent, see addEventListener vs onclick.

disable function using javascript

I can not seem to find the code to disable a javascript function. What I want to do is have a javascript function and then I want to disable it. Here is the code:
<script>
var fooFunc = function fooFunction() {
alert("HELLO");
};
$(document).ready(function() {
fooFunc.disable();
});
</script>
<button onclick="fooFunc()">Button</button>
Basically, when the button is click the function should not work, it should be disabled. Thanks
"Disabling" fooFunc is the same as setting it to an empty function (not to null--that will cause an error when it is called the next time). In this case:
$(document).ready(function() {
fooFunc = function() { };
});
But I don't see how this is different from simply removing the onclick handler from the HTML element.
If you want the ability to disable/re-enable the function, you can write it like this:
fooFunc = function() {
function _fooFunc() {
if (!enabled) return;
alert("HELLO");
}
var enabled = true;
_fooFunc.enable = function() { enabled = true; };
_fooFunc.disable = function() { enabled = false; };
return _fooFunc;
}();
If you want to extend this to allow any function to be enabled/disabled, you can write a higher-order function, which takes any function as a parameter, and returns a function with enable and disable methods attached to it:
function disablable(fn) {
function inner() {
if (!enabled) return;
fn();
}
var enabled = true;
inner.enable = function() { enabled = true; };
inner.disable = function() { enabled = false; };
return inner;
}
Now you can define fooFunc as
var fooFunc = disablable(function fooFunction() {
alert("HELLO");
});
and the rest of your code will work as you want.
You can access the onclick property of the element..
<button id="id" onclick="fooFunc()">Button</button>
<script>
document.querySelector('#id').onclick = '';
</script>
If you don't want the function to work at all and be totally disabled then use the below.
If you want the function to work only under certain conditions then you will need if/else statements so it will work only when the conditions that you have set are met.
$(document).ready(function(){
$("button").onclick(function(event){
event.preventDefault();
});
});
You were going to define it back to undefined or null.
fooFunc=undefined;
You Should be doing this :) Change function definition on very first run and you are good to go.
<! DOCTYPE html>
<html lang="en">
<body>
<script>
var fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
var enablefooFunc = function()
{
fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
}
</script>
<button onclick="fooFunc()">Run once and Disable FooFunc</button>
<button onclick="enablefooFunc()">Enable FooFunc</button>
</body>
</html>

Javascript "this" issue in Model View Presenter design

The issue is in the model, when recalled by the presenter it does not work like I assumed, in fact it works as if the this keyword refers to an [object HTMLTextAreaElement], not to a Model object.
/** PRESENTER **/
function Presenter() {
var toolbarView;
var outputView;
var sourceCodeModel;
var public = {
setToolbarView: function (view) {
toolbarView = view;
},
setOutputView: function (view) {
outputView = view;
},
setModel: function (_model) {
sourceCodeModel = _model;
},
init: function () {
toolbarView.setNewTableHandler(function () {
outputView.updateSource(sourceCodeModel.string);
});
toolbarView.setNewConstraintHandler(function () {
/*stub*/
alert("new constraint");
});
}
}
return public;
}
/** TOOLBAR VIEW **/
function toolbarView() {
this.setNewTableHandler = function (handler) {
$("#newTable").click(handler);
}
this.setNewConstraintHandler = function (handler) {
$("#newConstraint").click(handler);
}
}
/** OUTPUT VIEW **/
var outputView = {
updateSource: function (newVal) {
$("#sourcetext").val(newVal);
},
draw: function () {
//stub
}
};
/** MODEL **/
var model = new Object(); //o {};
model.source = [];
model.string = function () {
/* ALERT(this) returns [object HTMLTextAreaElement] wtf? */
var stringa = "";
for (var i = 0; i < this.source.length; i++) { //this does not work, since this = HTMLTextAreaElement
stringa += this.source[i] + "\n";
}
return stringa;
}
$(document).ready(function () {
var presenter = new Presenter();
var view1 = new toolbarView();
presenter.setToolbarView(view1);
presenter.setOutputView(outputView);
presenter.setModel(model);
presenter.init();
});
and the HTML is pretty simple:
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="mvp.js"></script>
<meta charset="UTF-8">
<title>Titolo documento</title>
<style type="text/css">
/*unnecessary here*/
</style>
</head>
<body>
<div id="container">
<div id="toolbar">
<button id="newTable">New table</button>
<button id="newConstraint">New Constraint</button>
</div>
<div id="source">
<textarea id="sourcetext"></textarea>
</div>
<button id="update">Update</button>
<div id="output"></div>
</div>
</body>
</html>
What am i doing wrong on the model object?
When you pass a function as a listener the this property will not be available inside the function:
var obj = {
a: function() {
alert(this)
}
};
$('body').click(obj.a);
When body is clicked the function's this property will be document.body.
To prevent this you must bind the function:
$('body').click(obj.a.bind(obj));
Or in older browsers wrap it:
$('body').click(function() {
obj.a();
});
So you must bind the function before pass it:
outputView.updateSource(sourceCodeModel.string.bind(sourceCodeModel));
More info about javascript function's context: http://www.quirksmode.org/js/this.html
this line: var public = { try to do not to use public, that is reserved word.
And a general note, try to bind this to a variable, because this changes context where it is currently.
/** TOOLBAR VIEW **/
function toolbarView() {
var that = this;
that.setNewTableHandler = function (handler) {
$("#newTable").click(handler);
}
that.setNewConstraintHandler = function (handler) {
$("#newConstraint").click(handler);
}
}

JavaScript onload and DOM

I have this example document:
<html>
<body>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
<div id="myDiv"></div>
</body>
</html>
Why 'element' is null if myFunc is a callback of document.body.onload?
If, instead, the script is inserted after the div, it works:
<html>
<body>
<div id="myDiv"></div>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
</body>
</html>
My question is: if I use the onload event within the handler function, should I have the entire DOM, or not? Why should I not?
The problem is that you are calling the function immediately (and assign its return value).
Assign the function instead and it will work:
document.body.onload = myFunc;
You should also use var element in your function to avoid creating a global variable.
Or if you want to confuse people:
document.body.onload = myFunc();
function myFunc() {
return function() {
var element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
};
}
But let's not do that. It makes no sense here. ;)
Use this instead
document.body.onload = myFunc;
Or
document.body.onload = function() {
myFunc();
};

Passing in defaults within window.onload?

I now understand that the following code will not work because I'm assigning window.onload to the result of the function, not the function itself. But if I remove the parens, I suspect that I have to explicitly call a separate function to process the config before the onload. So, where I now have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<script type="text/javascript" src="lb-core.js"></script>
<script type="application/javascript">
var lbp = {
defaults: {
color: "blue"
},
init: function(config) {
if(config) {
for(prop in config){
setBgcolor.defaults[prop] = config[prop];
}
}
var bod = document.body;
bod.style.backgroundColor = setBgcolor.defaults.color;
}
}
var config = {
color: "green"
}
window.onload = lbp.init(config);
</script>
</HEAD>
<body>
<div id="container">test</div>
</body>
</HTML>
I imagine I would have to change it to:
var lbp = {
defaults: {
color: "blue"
},
configs: function(config){
for(prop in config){
setBgcolor.defaults[prop] = config[prop];
}
},
init: function() {
var bod = document.body;
bod.style.backgroundColor = setBgcolor.defaults.color;
}
}
var config = {
color: "green"
}
lbp.configs(config);
window.onload = lbp.init;
Then, for people to use this script and pass in a configuration, they would need to call both of those bottom lines separately (configs and init). Is there a better way of doing this?
Note: If your answer is to bundle a function of window.onload, please also confirm that it is not hazardous to assign window.onload within scripts. It's my understanding that another script coming after my own could, in fact, overwrite what I'd assigned to onload. With that in consideration, it's best to expect your script user to call the function on initialization himself.
Use an anonymous function to pass options, like this:
window.onload = function() { lbp.init(config); };
If you're worried about getting overwritten take the unobtrusive route, like this.
Alternatively you can use a library for your javascript needs, for example I use jQuery for this, and it would look like this:
$(function() { lbp.init(config); });
Getting a library for only this is overkill, but if you have lots of javascript going on, I'd suggest you take a look at what's available.
You could return an anonymous function as a result of calling the init. Something like this:
var lbp = {
defaults: {
color: "blue"
},
init: function(config) {
for(prop in config){
setBgcolor.defaults[prop] = config[prop];
}
return function() {
var bod = document.body;
bod.style.backgroundColor = setBgcolor.defaults.color;
};
}
}
window.onload = lbp.init({color: "green"});

Categories

Resources