I am trying to use an object I am creating from a button click event. The object is available later in the code. The last console statement prints undefined. How can I return the object for use later in the code? Thank you.
const btn = document.getElementById('btn');
// Use IIFE to get human data from form
var getUserData = (
function () {
function getInput() {
let formContainer = document.getElementsByClassName('form-container')[0];
// Remove form from screen
formContainer.classList.add('hide');
//formContainer.style.display = 'none';
let main = document.getElementById('grid');
main.classList.remove('hide');
main.classList.add('show');
//main.style.display = 'flex';
let name = document.getElementById('name').value;
let feet = document.getElementById('feet').value;
let inches = document.getElementById('inches').value;
let height = (feet * 12) + inches;
let weight = document.getElementById('weight').value;
let diet = document.getElementById('diet').value;
return { name: name, height: height, weight: weight, diet: diet};
}
return(getInput);
})();
let human;
document.getElementById("btn").addEventListener("click", function (event) {
event.preventDefault();
var user = getUserData();
human = new Human(user.name, user.height, user.weight, user.diet);
getHumanInfo(); // console logs the human
return human; // returns udefined when I try to console log later in code
});
function getHumanInfo(){
console.log(human);
}
// this returns udefined
console.log('Human: ' + human);
You are adding an event listener, so the callback won't be called before a click is performed on the element with the id btn. And you are logging the variable human immediatly: it won't be defined because it hasn't been set yet.
Related
I am calling a method and want to have that method get the value of the returned value of the second method, to be able to use the variable in an element.
I always was able to call a function by putting the function in the other function. It seems when using classes I am unable to achieve this.
Do I have to use a callback method of some sort. I am new to classes.
class Bills{
constructor(amount,payment,duedate,apr){
this.amount = amount;
this.payment = payment;
this.duedate = duedate;
this.total = total;
this.apr = apr;
}
amountByMonth(billings){
//This is the function I am calling inside the function to get the value of.
let dueDays = daysLeft(billings);
const items = document.getElementById('bills');
const newitem = document.createElement('ul');
newitem.innerHTML = `
<li>Monthly Amount Due :${billings.amount}</li>
<li>Monthly Amount Due :${dueDays}</li>
<li>Total On Card: ${billings.total}</li>`;
items.appendChild(newitem);
}
daysLeft(billings){
let date1 = new Date();
let dueDate = new Date(billings.duedate);
let timeDiff = Math.abs(dueDate.getTime() - date1.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
return diffDays;
}
}// end
document.getElementById('subBtn').addEventListener('click',valueinput);
function valueinput(e){
let amount = document.getElementById('payment').value;
let total = document.getElementById('total').value;
let duedate = document.getElementById('dues').value;
let billings = new Bills();
billings.amount = amount;
billings.duedate = duedate;
billings.total = total;
billings.daysLeft(billings);
billings.amountByMonth(billings);
e.preventDefault();
}
You need to make it clear that you are calling another method of the same class and not a different function by using this:
When you declare a class method without the function keyword, you're basically declaring it as a functional property of the class object. To refer back to the property, you need to put it in the context of the object it's defined in, i.e.
let dueDays = this.daysLeft(billings);
You must use this, for example if you want to call function inside the class function you must use this to your class knows the reference. So your code should looks like:
amountByMonth(billings){
let dueDays = this.daysLeft(billings);
// Rest of your code
}
I need to make reset button which makes Resetting Scores. Can anyone help me?
I tried all my best but I don't know how to make it.
https://github.com/SandroGamrekelashvili/New-folder
const game = () => {
let pScore = 0;
let cScore = 0;
});
const startGame = () => {
const playBtn = document.querySelector(".intro button");
const introScreen = document.querySelector(".intro");
const match = document.querySelector(".match");
There were a few things you needed to get done to make the reset work.
1.) Assign reset button element to a const.
2.) Move your score elements to parent scope.
const game = () => {
let pScore = 0;
let cScore = 0;
const resetBtn = gameContainer.querySelector("button.startOver");
const playerScore = document.querySelector(".player-score p");
const computerScore = document.querySelector(".computer-score p");
// The rest of your code...
2.) Attach event listener to reset button.
const startGame = () => {
playBtn.addEventListener("click", () => {
introScreen.classList.add("fadeOut");
match.classList.add("fadeIn");
});
resetBtn.addEventListener("click", () => {
playerScore.innerText = '0';
computerScore.innerText = '0';
pScore = cScore = 0;
});
};
Here is a JSFiddle with a working example.
I think what you need to solve your problem is very well explained in this other questions here.
The idea is that instead of declaring your variable inside your main function, you would create a variable that refer to your functions related to your score outside of it that can then be called when you need it. To avoid global conflict, you would have that function return an object with functions inside for getters and setters. In your case, I would do something like this:
const scoreModule = () => {
let pScore = 0;
let cScore = 0;
return {
getPScore: () => pScore,
getCScore: () => cScore,
setPScore: value => pScore = value,
setCScore: value => cScore = value,
}
}
Because you defined the scoreModule as a global object, you can then use it wherever you want. And, because you returned only getters and setters (not the actual value, but rather a mean to get or change them) your object is protected and you avoid the bad practice of globally available variables. Then in any of your other functions, when you want to use them either to get or set them, you simply:
const game = () => {
// To get a score
const currentPScore = scoreModule().getPScore()
// To set a score
scoreModule().setPScore(newScore)
});
I'm working on a page in which one element ('.item--itemprice') updates its text through another function that I'd prefer not to touch. What I'd like to do is get another element ('.header--itemprice') to update so that its text matches the first element.
Unfortunately, it seems that handler below is acting faster than the updating function. As a result, the header either stays with the previous text or changes to a blank string. Is there a way to delay the final line below until after the first element is finished updating?
$('select').on('change', function() {
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
});
Here's the preexisting function:
$(document).ready( function () {
$('#txtQuantity, .ProductGroupItemQuantity').blur(updatePrice);
});
function updatePrice() {
var itemPriceEl = $('.item--itemprice');
var itemCountEl = $('#txtQuantity');
var groupUpdateEl = $('#lnkProductGroupUpdatePrice');
var groupPriceEl = $('.pdetail--price-total');
var totalPriceEl = $('.ProductDetailsPricing');
var itemPrice = moneyToNumber(itemPriceEl.text());
var itemCount = moneyToNumber(itemCountEl.val());
var itemTotalPrice = itemCount * itemPrice;
var groupTotalPrice = 0;
// Trigger Group Update
groupUpdateEl.click();
groupTotalPrice = moneyToNumber(groupPriceEl.text());
// Calculate Total Price
totalPriceEl.text('Total: $' + Number(groupTotalPrice + itemTotalPrice) / 100);
}
/*$('select').on('change', function() {
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
});*/
function moneyToNumber(moneyEl) {
try {
return Number(moneyEl.replace(/[^0-9\.]+/g,"").replace(/\D/g,''));
} catch (err) {
return 0;
}
}
If you don't want to touch the other function at all and assuming it is also being called on the change event of select. A really hacky way could be, something like this -
$('select').on('change', function() {
setTimeout (function()
{
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
}, 0);
});
In that case, the better way is changing the function, you can even trigger a event when the function is executed and watch this event to trigger the other function to change the element ('.header--itemprice')
I understand that in D3, dispatch can be used to fire events to multiple visualisations according to this example.
I also understand that if I want to call a dispatch from an object and pass in the context, I can use apply as shown here.
However, I'm having a hard time combining the arguments from a D3 dispatch and the context that I want.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse);
// this next line isn't working, since the
// console.log in probeLoad still returns undefined
probeDispatch.probeLoad.apply(this);
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
new genChart("pants");
new genChart("shirt");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
It does set the context properly when you see "pants" in the console.
But then there are 3 undefined's logged, because you also call
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
without supplying context.
You need
probeDispatch.probeLoad.apply(instanceOfGenChart, [lines[line_count][0], lines[line_count][1]]);
But enabling that also requires moveing parse_dispatch down the page.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse);
// this next line isn't working, but I don't know what to do
probeDispatch.probeLoad.apply(this);
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
var instanceOfGenChart = new genChart("pants");
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad.apply(instanceOfGenChart, [lines[line_count][0], lines[line_count][1]]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
So it turns out to bring the context into the function, I have to bind() it for reasons I'm not too clear on.
// create my dispatcher
var probeDispatch = d3.dispatch("probeLoad");
var line_count = 0;
// load a file with a bunch of JSON and send one entry every 50 ms
var lines = [[0,1],[1,2],[2,0]];
var parse_timer = window.setInterval(
function () {
parse_dispatch();
}, 50
);
function parse_dispatch(){
// send two arguments with my dispatch
probeDispatch.probeLoad(lines[line_count][0], lines[line_count][1]);
line_count += 1;
if(line_count >= lines.length){
//line_count = 0
window.clearInterval(parse_timer);
}
}
// my chart object
var genChart = function(label){
this.label = label;
// assume I've drawn my chart somewhere here
probeDispatch.on(("probeLoad."+this.label), this.probeParse.bind(this));
};
genChart.prototype = {
probeParse: function(probeData, simTime) {
// How do I get the context from the object that's calling probeParse
// into the probeParse scope?
var self = this;
console.log(self.label);
}
};
new genChart("pants");
new genChart("shirt");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Added by meetamit
Bind is the solution here, because it locks a scope to an "instance" of genChart.prototype. probeParse. This way parse_dispatch (the invoker) doesn't need to know anything about scope. It's equivalent to this:
// my chart object
var genChart = function(label){
this.label = label;
var self = this;
var probeParseBound = function() { self.probeParse(); };
probeDispatch.on(("probeLoad."+this.label), probeParseBound);
};
I'm trying to call a method cardSelection() from a function game() but instead I'm getting an error report which throws back to me the whole function with a "has no method cardSelection()" The idea is to access the method through the click of a button, which HTML tag is as follows:
<img id="PlayerCard0" class="card" src="images/Cards/Mario.png" alt="Mario" title="Mario" onclick="game.cardSelection('PlayerCard0')">
I'm not posting the whole Javascript as I believe this to be the case of a mere declaration error, anyhow, game() and cardSelection() were declared as follows:
function game()
{
...
this.cardSelection = function(card)
{
var cardElem = document.getElementById(card);
var id = cardElem.getAttribute("id");
var call = document.getElementById("call");
var select = function(card)
{
var found = 0;
for (var card = 0, totalCards = 5; card < totalCards; card++)
{
if (document.getElementById("PlayerCard" + card + "selected"))
{found++}
}
if (found == 0)
{
call.setAttribute("onclick", "changeHand()");
call.childNodes[0].nodeValue = "Change";
}
if (found < 3)
{
id += "selected"
setAttributes(cardElem,
{
"id" : id,
"style": "position: relative; top: 1em;",
"onclick" : "cardSelection('" + id + "')"
});
}
else { return; }
}
var unselect = function (card)
{
cardElem.removeAttribute("style");
id = id.replace("selected","");
setAttributes(cardElem,
{
"id" : id,
"onclick" : "cardSelection('" + id + "')"
});
var cardNumber = 0;
var found = false;
while (cardNumber < 5 && !found)
{
if (document.getElementById("playerCard" + cardNumber + "selected"))
{found = true;}
cardNumber++;
}
if (!found)
{
call.setAttribute("onclick", "compareHands()");
call.childNodes[0].nodeValue = "Hold";
}
}
if (id.indexOf("selected") >= 0){unselect(card);}
else {select(card);}
}
...
}
How game() is called:
window.onload = function openingScreen()
{
var startGame = document.createElement("a");
startGame.setAttribute("onclick", "game()");
startGame.appendChild(document.createTextNode("Play"));
window.table = document.getElementById("table");
table.appendChild(startGame);
}
The problem you are experiencing is the result of confusion about Objects/Classes/Instances in javascript.
The critical point for you on this issue is the difference between new game() and game();
var foo = new game()
tells the JS engine to create a new object
point that object's Prototype (not prototype) at game's prototype
and then invoke the function game, but for the sake of the body of that function this will refer to the created object.
If the function doesn't return an object, assign our created object to foo (otherwise assign the function's return value to foo
Inside the body of your game function, you have this.cardSelection = function (....
If you simply invoke game as a function, so just game(), without the new keyword, this inside the body of the function will be the window object! So you'll add cardSelection to the window object.
Also importantly: game.cardSelection() is looking for a function named cardSelection as a property on the function game.
Here's an example of using that style that would work:
var foo = function () {
//do interesting stuff
}
foo.bar = function () {
//do interesting stuff related to foo
}
foo.bar();
What you seem to be expecting would need to be written this way:
var game = function () {
this.cardSelection = function () {
//perform card selection!
}
}
var aGame = new game();
aGame.cardSelection();
Or, if cardSelection does not need access to any private properties of the game, it could be written more efficiently as
var game = function () {
//setup the game
};
game.prototype.cardSelection = function () {
//perform card selection
};
var aGame = new game();
aGame.cardSelection();