Passing in defaults within window.onload?
- by Matrym
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.