how to use one function variable in another function in javascript - javascript

I want to access one function variable in another function,
My first function and variable
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
var max = this.volume.header.imageDimensions.zDim;
}
My second function
papaya.Container.fillContainerHTML = function(){
// I want to access max value here
}
I want to access the max value to a second function,
I tried many ways to do but I can't able to make it.

Just declare max as a global variable, outside the functions, where it can be accessed by both, like so:
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
max = this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
// You can now access max value here
}
If it doesn't work, send an online demo so we can help.

You can return this value and get from fillContainerHTML
papaya.viewer.Viewer.prototype.pagination = function () {
return this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
var view = new papaya.viewer.Viewer();
var a = view.pagination();
console.log(a);
}

The Best and easiest solution to your question
Hi. I had researched a lot about the question you are asking. I watched many tutorials, but they were really complicated. So once, I was working on a project. I didn't realise, but I used a variable created/edited in a function in another function. It was really simple. You need to create Local Storage to do this. The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. It is Supported in almost every famous or known web browser like Google Chrome, Firefox, Opera, safari, Microsoft Edge etc.
Note: if you click Run code snippet button, the code won't work because Stack Overflow doesn't support Local Storage. So, go to another text editor like notepad, run the code, and see the result on any Browser (mentioned above). It will work.
// Creates a variable
var max = "Nothing";
function btn1() {
// Makes a change to max variable
var max = "Max variable changed";
// Creates Local Storage on browser
var setLocalStorage = localStorage.setItem("max", max);
}
function btn2() {
var getLocalStorage = localStorage.getItem("max");
document.ById("text").innerHTML = getLocalStorage;
}
<html>
<body>
<p id="text"> Nothing </p>
<button onclick="btn1()"> Make change </button>
<button onclick="btn2()"> See change </button>
</body>
</html>

Related

Javascript not setting this to value with apply or call

Edit: the code below was made up on the spot to show how I was going about what I was doing. It definietely won't run, it is missing a lot of things.
Here is a working example in codepen: https://codepen.io/goducks/pen/XvgpYW
much shorter example: https://codepen.io/goducks/pen/ymXMyB
When creating a function that is using call or apply, the this value stays null when using getPerson. however, when I use apply or call with getPerson it returns the correct person.
Please critique, I am really starting to learn more and more. I am in the middle of a project section so it might be hard to change all the code, but my next project could implement this better.
call and apply are setting to the window and not the object.
I will provide code that is much simpler with the same concept of what I am talking about.
function createPerson(){
this.manager = null;
this.teamManager = null;
this.setTeamManager = function(val){
this.teamManager = val;
}
this.setManager = function(val){
console.log('setting manager to',val);
this.teamManager = val;
}
this.getTeamManager = function(){
console.log('setting team manager to',val);
return this.teamManager ;
}
this.getManager = function(){
return this.manager;
}
this.appendSelect = function(elem){
var that = this;
createOtherSelects(that,elem);
}
//some functions that create selects with managers etc
//now assume there are other selects that will filter down the teams,
//so we might have a function that creates on change events
function createOtherSelects(that){
//code that creates locations, depending on location chosen will
//filter the managers
$('#location').on('change',function(){
//do some stuff
//... then call create management
createManagement(that,elem);
});
}
function createManagement(that,elem){
var currentLocation = that.location; //works
var area = that.area;//works ... assume these are set above
//code that returns a filter and unique set of managers back
that.teamManager = [...new Set(
data.map(person=>{
if(person.area==area &&
person.currentLocation==currentLocation
){
return person;
}
})
)].filter(d=>{if(d){return d}});
if(elem.length>0){
var selectNames = ['selectManager','selectTeamManager'];
var fcns = [that.setManager,that.setTeamManager];
for(var i = 0; i < selectNames.length;i++){
//do stuff
if(certainCriteriaMet){
// filter items
if(filteredManager == 1){
fcns[i].call(null,currentManager);//
}
}
}
}
}
}
var xx = new createPerson()
In console I see setting manager and setting team manager to with the correct values.
however when I call xx in console, I see everything else set except for
xx.teamManager and xx.manager
instead it is applying to the window, so if I type teamManager in the console, it will return with the correct person.
If I straight up say
that.setManager('Steve')
or even it works just fine.
xx.setManager('steve')
the this value in setManager is somehow changing from the current instance of the object to this window. I don't know why, and I would like to learn how to use apply and call using that for future reference.
I think the issue is with your following code
fcns[i].call(null,currentManager)
If you are not supplying "this" to call, it will be replaced with global object in non-strict mode.
fcns[i].call(that,currentManager)
See mdn article here
From your codepen example, you need to change that line
fcnset[0].apply(that,[randomName]);
The first argument of the apply method is the context, if you are not giving it the context of your method it's using the global context be default. That's why you end up mutating the window object, and not the one you want !

Im building a clicker game and localstorage is returning with nothing instead of saved data

So I'm building a clicker game on CodePen and I ran into a problem while coding my save/load functions. It seems as if my save function may not me working, but I'm not sure why.Here are the functions:
function savegame(){
localStorage.clicks = Number(document.getElementById('clicks').innerHTML);
localStorage.cps = document.getElementById('cps').innerHTML;
localStorage.clickPower =
Number(document.getElementById('clickpower').innerHTML);
localStorage.onecpow = Number(document.getElementById('1clickpowe').innerHTML);
localStorage.onecps = Number(document.getElementById('1cps').innerHTML);
localStorage.fivecps = Number(document.getElementById('5cps').innerHTML);
localStorage.fivecpow = Number(document.getElementById('5clickpower').innerHTML);
localStorage.tencps = document.getElementById('10cps').innerHTML;}
function loadgame(){document.getElementById('1clickpower').innerHTML = localStorage.getItem("onecpow");
document.getElementById('clicks').innerHTML = localStorage.getItem("clicks");
document.getElementById('cps').innerHTML = localStorage.getItem('cps');
document.getElementById('clickpower').innerHTML = localStorage.getItem('clickpower');
document.getElementById('5clickpower').innerHTML = localStorage.getItem('fivecpow');
document.getElementById('5cps').innerHTML = localStorage.getItem('fivecps');
document.getElementById('1cps').innerHTML = localStorage.getItem('onecps');
document.getElementById('10cps').innerHTML = localStorage.getItem('tencps');}
I forgot to clarify what I'm expecting the code to do. What this should do is save the players progress and upgrades, instead upon loading the saved data the players data is not loaded and returns many blank spaces where saved data should have been loaded.
Instead of doing localStorage.onecpow = "someValue" try
storage.setItem(onecpow, "someValue");
You can check the Storage docs here for more info
You are using 'localStorage' wrong. Have a look at this:
// writing to localStorage
localStorage.setItem('myId', value);
// reading from localStorage
var whatever = localStorage.getItem('myId');
// remove an item from localStorage
localStorage.removeItem('myId');
EDIT:
The problem is that you're mixing up 2 different approaches. You have to decide which one to use. Either the object-driven or the key-driven.
My example above is the key-driven approach. You should also be able to use the object-driven approach like this:
// writing to localStorage
localStorage.myObject = value;
// reading from localStorage
var whatever = localStorage.myObject;
Choose your style, but don't mix them. ;o)
I found a solution, though it's kind of strange how it works.
I added capital letters to the localStorage attributes and used localStorage.setItem and localStorage.getItem. Don't know why it works but it does.

Returning empty string on a input that has a value

I have a date input in my page, which I'm using Daterangepicker framework to populate it.
Here is the code of how I start my page!
$(function(){
startSelectors();
var variaveis = returnInputVars();
var rede = variaveis[0];
var codLoja = variaveis[1];
var period = variaveis[2];
console.log('1.'+rede+' 2.'+codLoja+' 3.'+period);
});
function returnInputVars(){
var rede = $("#dropdown-parceria").val();
var codLoja = $("#dropdown-loja").val();
var periodo = $("#datepicker-range").val();
return [rede, codLoja, periodo];
};
The function startSelectors() is set to start my datepicker and other fields, which is working perfectly. After it, I create a var called "variaveis" to fill
with the values of each field because I will use then later (this functions also works perfectly at other scripts of my page).
Running the page, my console returns this:
The funny thing is, if I type at the console this, the value is shown, just while starting the script is does not work!
Anybody experienced something like this?
***UPDATE
Adding this script to my start function:
console.log($("#datepicker-range"));
The value is shown, but the second console.log don't:
EDIT 1. FIDDLE (Suggested by #halleron)
To ensure things are loaded in the correct order, it is useful to apply a page sniffer code snippet that will scan the page continuously until a condition is met, or until a preset counter limit is reached (to prevent strain on browser memory). Below is an example of what I typically use that would fit your scenario.
I think because you are dealing with asynchronous loading, you can't have a global variable that holds the values in a global scope without an interval to detect when it can be used. Otherwise, it will attempt to read the variable when it is not yet ready.
You can invoke functions anywhere you like. But I would keep all of your variables contained within the page_sniffer_2017() because that is a controlled environment where you know that everything successfully loaded and you know that the variables are ready to be accessed without error.
That way, regardless of connection speed, your functions will only fire when ready and your code will flow, sequentially, in the right order.
Within the ajax success options, always add a class to the body of the document that you can search on to determine if it has finished loading.
$(document).ready(function() {
page_sniffer_2017();
});
function page_sniffer_2017() {
var counter = 0;
var imgScanner = setInterval(function() {
if ($("#datepicker-range").length > 0 && $("#datepicker-range").val().length && jQuery('body').hasClass('date-picker-successfully-generated')) {
var periodoDatepicker = $("#datepicker-range").val(); // ok
console.log(periodoDatepicker); // ok
var variaveis = returnInputVars(replaceDate(periodoDatepicker)); // ok
console.log(variaveis[0], variaveis[1], variaveis[2]);
//startNewSelectors(variaveis);
// start ajax call
generateData(variaveis[0], variaveis[1], variaveis[2]);
clearInterval(imgScanner);
} else {
//var doNothing = "";
counter++;
if (counter === 100) {
console.log(counter);
clearInterval(imgScanner);
}
}
}, 50);
}

JQuery - using previously declared variables for a click function

Have searched high an low for an answer without luck.
I am trying to pass a variable between two functions. The first function runs when the page loads, pulling settings from a google script file. I don't have any issues with this part. I am however, struggling with the second function which runs 'on click' and requires some variables from the first function.
Any guidance is appreciated.
<script>
$(function() {
google.script.run
.withSuccessHandler(loadSettings)
.withFailureHandler(showStatus)
.withUserObject($('#button-bar').get())
.getSettings();
function loadSettings(settings) {
$("select").data("option",settings.userInput1);
};
$('#add1').click(function(){
var option0 = $("select").data("option");}
...etc.
})
</script>
I assume settings.userInput1 is a string. Try the below
<script>
var userInput ="";
$(function() {
google.script.run
.withSuccessHandler(loadSettings)
.withFailureHandler(showStatus)
.withUserObject($('#button-bar').get())
.getSettings();
function loadSettings(settings) {
userInput = settings.userInput1;
$("select").data("option",settings.userInput1);
};
$('#add1').click(function(){
//you can now use userInput in this function
var option0 = $("select").data("option");}
...etc.
})
if other solutions are not working then you should go this way -
Make a hidden field
store that variables value in that hidden field
in the next function get the value from that field
$("#hiddenfield_id").val();

Difference between two similar functions, why is one working and the other not

I have two functions, one working, the other not.
They are equal, except that the one is looping through a variable, in which the global object of the scope is saved (hope this makes sense), and the other tries to loop through the text directly, but fails, because it throws the error:
Uncaught TypeError: Cannot read property '0' of undefined
Here is the fiddle:
http://jsfiddle.net/4p1p4wjy/2/
In my understanding, the 2nd version of the function is not working, because it somehow can't access the this.splittedText, from within the callback of the function.
First Working Function:
loopThroughSplittedText: function() {
// delete this
var locationInString = 0;
var splittedText = this.splittedText;
function delayedOutput() {
document.getElementById('output').innerHTML = splittedText[locationInString];
locationInString++;
if(locationInString < splittedText.length) {
setTimeout(delayedOutput, 200);
}
}
delayedOutput();
},
Second Not Working Function:
loopThroughSplittedTextNotWorking: function() {
// delete this
var locationInString = 0;
function delayedOutput() {
document.getElementById('output').innerHTML = this.splittedText[locationInString];
locationInString++;
if(locationInString < this.splittedText.length) {
setTimeout(delayedOutput, 200);
}
}
delayedOutput();
}
How do I make the 2nd function work, without saving the object inside a local variable first? I'd like to use the two-way databinding as best as possible.
How do I make the 2nd function work, without saving the object inside a local variable first?
You can't. this is a variable that is always local to the function it is used in, and its value depends on how the function is called. If you want to use its value in a different function, then you need to copy it into another variable.
The bind method provides a shorthand for doing that.
setTimeout(delayedOutput.bind(this), 200);
Simple answer, you don't.
Because your function is called through timeout, it's not in the same context anymore and 'this' will not refer to the same object anymore.
You can do this:
loopThroughSplittedTextNotWorking: function() {
// delete this
var locationInString = 0;
var that = this;
function delayedOutput() {
document.getElementById('output').innerHTML = that.splittedText[locationInString];
locationInString++;
if(locationInString < that.splittedText.length) {
setTimeout(delayedOutput, 200);
}
}
delayedOutput();
}
By saving the "this" variable into a local variable, you can access it in your "delayedOutput" function.
I realize it's basically just like your working example, just phrased a little different, but that's usually how I do it.

Categories