I have a question regarding Node.js that I started using recently and I don't have much dexterity yet.
So, I have a function inside the pages.js file and I need some values to be passed to HTML in the same way that was done with "arrayOfCookies", (passing to the router that is also in pages.js). However what I understood is that the function needs to return next () for the page to be loaded. Is there any way to pass these values (7 variables) to the router.get in a similar way to what I have already done with cookies? My goal is to display those in my HTML. I appreciate any help, my code is below - Im not going to put my function here cause i guess its not relevant to answer my question.
router.get('/userPage',beforeReq,authFunct,(req,res) =>{
var arrayOfCookies = req.cookies['myEmail'];
///exercises1,exercises2,exercises3,exercises4,exercises5,exercises6,exercises7 are the variables that i need to pass from my function to the line below. They are all arrays
res.render('userPage', {name: arrayOfCookies})
And this is just a part of the function that I want to pass the values of
function beforeReq(req,res,next){
var allExercises = []
var exercises1 = []
var exercises2 = []
var exercises3 = []
var exercises4 = []
var exercises5 = []
var exercises6 = []
var exercises7 = []
return next()
}
Related
I want to use the following (creating a gallery card with information being provided through array for initial and a form for adding additional) I've been able to get the following function to work on information being added through the form but have not been able to get the function to work on the array I have.
function galleryAddItems(image, title){
const galleryElement = galleryTemplate.cloneNode(true);
galleryElement.querySelector(".gallery__image").src = image;
galleryElement.querySelector(".gallery__text").textContent = title;
galleryContainer.prepend(galleryElement);
}
on the array I have
const initialCards = [
{
name: "The End Place",
link: "images/cliffside__Katie-Rodriguez.jpg"
},
{
name: "Turn That Leaf Over",
link: "images/leaf__chuttersnap.jpg"
},
...
];
Currently have a second function set as
initialCards.forEach(function(thingy){
const galleryElement = galleryTemplate.cloneNode(true);
galleryElement.querySelector(".gallery__image").src = thingy.link;
galleryElement.querySelector(".gallery__text").textContent = thingy.name;
galleryContainer.append(galleryElement);
});
For this specific instance and want to avoid duplicating the code to make this work.
I've previously had galleryAddItems include .value in the function as it's needed in a different place but added that when it's being called with the hopes of it working here.
I've tried
initialCards.forEach(galleryAddItems(link, name))
and tried things like initialCards.link/.name
initialCardsLink/initialCardsName
If I don't put in parameters I'm not getting the image URL working and index is placed where I'm looking to have the name/title.
An easy way without changing your galleryAddItems() function would be:
initialCards.forEach(thingy => galleryAddItems(thingy.link, thingy.name));
Personally, I would probably think about changing the first function to something like:
function galleryAddItems(image) {
const galleryElement = galleryTemplate.cloneNode(true);
galleryElement.querySelector(".gallery__image").src = image.link;
galleryElement.querySelector(".gallery__text").textContent = image.name;
galleryContainer.prepend(galleryElement);
}
so that you could simply do:
initialCards.forEach(galleryAddItems);
You need to pass a function to the forEach function, currently, you're passing the return value of galleryAddItems since you're calling it.
I would suggest refactoring your code so that galleryAddItems takes a card as a parameter and then call it for each card using forEach.
function galleryAddItems(card){
const galleryElement = galleryTemplate.cloneNode(true);
galleryElement.querySelector(".gallery__image").src = card.link;
galleryElement.querySelector(".gallery__text").textContent = card.name;
galleryContainer.prepend(galleryElement);
}
// Call galleryAddItems for each card
initialCards.forEach(galleryAddItems)
I've been trying to implement some card game using Javascript. In the snippet below, I simply want to pull two cards from the top of the deck and give it to the player (simplified logic below)
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard() {
var singleCard = deck().pop();
var faceValue = singleCard[0];
return faceValue;
}
var cardPair = [removeCard(),removeCard()];
console.log(cardPair);
However the faceCards array is still the same even after popping off its cards which means that the next card will be the same as well as seen in cardPair array.
I need to mirror the effects I used inside of the
removeCard() function to reflect back in the deck() function.
I suppose I could either create the faceCards array in the global scope or use 'this' in some way (which I don't really want as I'm not much familiar with it). How can I update one function from inside another function? Thank you very much for reading this.
Your error is here:
var singleCard = deck().pop()
The call to deck() creates a new array of cards every time it's called, and doesn't repeatedly return the same array.
If you don't want to go full OO yet, consider at least passing the deck as a parameter to the removeCard() function, i.e.
function removeCard(deck) {
var singleCard = deck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var deck = newDeck();
var pair = [ removeCard(deck), removeCard(deck) ];
but ultimately you should longer term be going for a full OO solution, where your usage might then become:
var deck = new Deck();
var pair = [ deck.takeCard(), deck.takeCard() ];
implementation of this is out of scope of this particular question.
You're creating a new array every time you run deck(). Try saving the deck in an array and running pop on this:
function deck() {
var faceCards = [['jack', 11],['queen', 12],['king', 13]];
return faceCards;
}
function removeCard(fromDeck) {
var singleCard = fromDeck.pop();
var faceValue = singleCard[0];
return faceValue;
}
var thisDeck = deck();
var cardPair = [removeCard(thisDeck),removeCard(thisDeck)];
console.log(cardPair);
I've tried to search for an answer to my question, but I'm starting to think that, given the lack of results, I'm obviously not expressing the question properly. With that in mind, apologies if the title of this post is misleading, I am still very much learning.
I have a simplified version of my code below
var testData = ['a', 'b']
var addReceiver = (function () {
dataReceiver = function (dataInput) {
t = this
t.data = dataInput;
console.log(t.data);
t.interval = setInterval(function () {
t.update();
}, 1000);
t.stopUpdate = function () { clearInterval(t.interval); };
t.update = function () {
//t.data = dataInput;
console.log(t.data);
};
};
})()
var testLogger = new dataReceiver(testData);
</script>
The behaviour that I wish to emulate is when I type into the console
testData = ['c','d','e']
for testLogger to log the array ['c','d','e'] every second rather than ['a','b'].
I could change
t.data = dataInput to t.data = testData
to achieve this, but that would obviously be pointless, or else every new instance I created of dataReceiver would have a reference to the same data input.
So, my question is, how would I need to change the code to provide the testLogger vairable (or any instance of dataReceiver) access to a variable outside of its local scope?
Use the object that you have created instead of accessing the global variable,
var testLogger = new dataReceiver(testData);
testLogger.data = [1,2,3,4];
Now you will be able to print the newly injected data. I mean the setInterval will print the updated value.
I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?
After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works
I'm working on a code where I must pass a different function to some objects.
In this case, I'm trying to pass a different function for the onchange event. So currently what I got is something like this this:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList){
var doFunction = function() {
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}
The problem here I believe is that I'm afraid it will execute the code as it is declared and not with the values of the actual variables.
Is there a way to pass the function with the values as it executes? or will the variables get parsed the way its written?
It's the classic function in a loop problem. You need to understand how closures work.
Read the "Example 3" part of this answer carefully. The whole How do JavaScript closures work? question, too.
Another example that might help understand intuitively:
var key = 5;
var onchange = function () {
console.log(key);
};
onchange(); // 5
key = 10; // the loop reassigns the key on each iteration
onchange(); // 10
This is how it should be done:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList)
{
(function(key)
{
var doFunction = function()
{
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}(key))
}