newbie Javscripter here. I'm trying to get some practice with modules and I'm hitting a wall. I'm trying to get the controller
module to access the wagerAmount
(input by user) from the UIControl
module with minimal success. My relevant code is as follows:
var UIControl = (function() {
return {
getWager: function() {
return {
wagerAmount: document.getElementById('wager').value
};
}
};
})();
var controller = (function(UICont) {
var topics = ['sports', 'history', 'technology', 'music', 'movies'];
var wager = UICont.getWager();
var changeClass = function() {
document.getElementById('bet').addEventListener('click', function() {
console.log(wager);
for (var i = 0; i < topics.length; i++) {
if (document.getElementById(topics[i]).classList[1] == 'select') {
activateAnswers();
}
}
});
}
})(UIControl);
When I run this, console.log(wager)
prints a empty string, {wagerAmount: ""}
. If I declare wager
inside the changeClass
function, the same thing happens. However, if I declare wager
inside the click event, it prints the number input by the user. BUT, the topics
variable, declared in the controller
is being accessed just fine by the click event. The main problem here is when I need to add the functionality to multiple click events, I would have to declare a new variable in each click event to access the same function, which sounds like bad practice. So what's going on here?
Ok, so after spending a couple hours last night trying to figure this out, I quickly figured out the solution this morning after some coffee. In case anyone else has this problem I'll post my solution, and if someone else comes up with something else, they can post as well.
Instead of declaring wager
in the controller
anywhere, I created a new function inside controller
:
var retrieveWager = function() {
return {
wager: UICont.getWager().wagerAmount
};
}
and then could access it in any of the click events like this:
retrieveWager().wager;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.