'Passing data up through nested functions in .js
Coding beginner here. I've got a page-js script below which when a dropdown is changed it triggers function getDrawNumOne, which in turn runs a function and retrieves two pieces of data from a GoogleSheet (drawNumReturnOne[0] & [1]). I want to pass the returned drawNumReturnOne[1] up through getDrawOneNum and then on into doStuff for use there - but am struggling on how to do this in a slick way, given I cannot call variables outside of their function scope. Do I need multiple returns up through the function stack or is there another, better way? All advice gratefully accepted, thanks.
document.getElementById("btn").addEventListener("click",doStuff);
document.getElementById("m_p1").addEventListener("onchange",getDrawNumOne);
function doStuff(){
var userInfo ={};
userInfo.m_p1 = document.getElementById("m_p1").value;
userInfo.m_s1 = ######;
google.script.run.userClicked(userInfo);
}
function getDrawNumOne(){
var drawNumOne = document.getElementById("m_p1").value;
google.script.run.withSuccessHandler(updateDrawNumOne).getDrawNo(drawNumOne);
}
function updateDrawNumOne(drawNumReturnOne){
document.getElementById("draw1").value = drawNumReturnOne[0];
###### = drawNumReturnOne[1];
}
Solution 1:[1]
In your situation, as a simple method, how about the following modification?
Modified script:
let sample = ""; // Added
document.getElementById("btn").addEventListener("click", doStuff);
document.getElementById("m_p1").addEventListener("change", getDrawNumOne); // Modified
function doStuff() {
var userInfo = {};
userInfo.m_p1 = document.getElementById("m_p1").value;
userInfo.m_s1 = sample; // Modified
google.script.run.userClicked(userInfo);
}
function getDrawNumOne() {
var drawNumOne = document.getElementById("m_p1").value;
google.script.run.withSuccessHandler(updateDrawNumOne).getDrawNo(drawNumOne);
}
function updateDrawNumOne(drawNumReturnOne) {
document.getElementById("draw1").value = drawNumReturnOne[0];
sample = drawNumReturnOne[1]; // Modified
}
- As another modification point, I thought that in your script,
onchangeofdocument.getElementById("m_p1").addEventListener("onchange",getDrawNumOne);ischange. But, if your situation can be used asonchange, please use it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tanaike |
