Reputation: 401
I have two objects defined, each one has an init function as follows
var TestSound = {
settings: {
testSoundFile : "static/main/persoonS",
postUrl : "dummy.com",
},
init : function(){
this.cacheDom();
this.bindEvents();
},
cacheDom: function(){
this.oneCertainButton = document.getElementById("buttonId");
this.soundElement = document.getElementById("sound");
},
bindEvents : function(){
that = this;
this.oneCertainButton.onclick = function(){ that.playSound(that.settings.testSoundFile); };
},
............
var CheckInput = {
settings: {
correctAnswer : "persoon",
},
init : function (){
this.cacheDom();
this.bindEvents();
},
cacheDom: function (){
this.submitButton = document.getElementById("submitButtonId");
this.answerInputBox = document.getElementById("answerId");
this.feedbackField = document.getElementById("feedbackId");
},
bindEvents: function(){
that = this;
this.submitButton.addEventListener("click", function(event){
..........
I wish to initialise them both (one after the other) with "window onload" like so:
window.onload = function() {
CheckInput.init.bind(CheckInput);
TestSound.init.bind(TestSound);
};
This doesn't work apparently as the init functions do not seem to be called.
However, it works if I initialise just one of the modules like so:
window.onload =
CheckInput.init.bind(CheckInput);
Any explanations on what is going wrong here much appreciated!
Upvotes: 0
Views: 508
Reputation: 664405
You want either
window.onload = function() {
CheckInput.init();
TestSound.init();
};
or
window.addEventListener("load", CheckInput.init.bind(CheckInput));
window.addEventListener("load", TestSound.init.bind(TestSound));
Any explanations on what is going wrong here much appreciated!
You have to create a function to be used as a handler that is called when the event fires. You can do that by using bind
or with a function expression, but if you use both then only another function will be created when the event happens, and the init
method is not called at all.
Upvotes: 1