Roll20 uses cookies to improve your experience on our site. Cookies enable you to enjoy certain features, social sharing functionality, and tailor message and display ads to your interests on our site and others. They also help us understand how our site is being used. By continuing to use our site, you consent to our use of cookies. Update your cookie preferences .
×

Setting change events in a loop

1502190677

Edited 1502190750
Hi all! I have a number of traits I want to sum some values for and I'm trying to dynamically create their "change:traitN" events on startup, iterating over a loop of the trait names and how many child fields the change event needs to cover. The issue is only the final on(change) event seems to be sticking around. var allTotals = { 'hack':4, 'hunt':4, 'read':4, 'scrounge':4, 'stress':9 }; // when sheet's opened, create on change events for all fields in allTotals var init = function() {     for (f in allTotals) {         var numFields = allTotals[f];         var changeStr = "";         for(i = 1; i <= numFields; i++) {             changeStr = changeStr + "change:" + f + i + " ";         }         on(changeStr, function(eventInfo) {             console.log('INIT():',eventInfo);             setTotal(f, numFields);         });         console.log('INIT():', changeStr, f, numFields);     } } In this case, changing Hunt or Scrounge or what have you only triggers the event for Stress.
1502212456

Edited 1502212692
Jakob
Sheet Author
API Scripter
I'm pretty sure this is a problem with variable scope. Try this variant: var allTotals = { 'hack':4, 'hunt':4, 'read':4, 'scrounge':4, 'stress':9 }; // when sheet's opened, create on change events for all fields in allTotals Object.entries(allTotals).forEach(([f, numFields]) => {         let changeStr = "";         for(let i = 1; i <= numFields; i++) {             changeStr = changeStr + "change:" + f + i + " ";         }         on(changeStr, function(eventInfo) {             console.log('INIT():',eventInfo);             setTotal(f, numFields);         });         console.log('INIT():', changeStr, f, numFields); }); EDIT: Just noticed that this is probably for some kind of Blades-derived game. Go go! :D
Thank you! Here's what I ended up with: var eventParams = [     {'name': 'hack', dots: 4},     {'name': 'hunt', dots: 4},     {'name': 'read', dots: 4},     {'name': 'scrounge', dots: 4},     {'name': 'stress', dots: 9} ]; eventParams.forEach(function(component) {     let changeStr = "sheet:opened";     for(let i = 1; i <= component.dots; i++) {         changeStr = changeStr + " change:" + component.name + i;     }     on(changeStr, function(eventInfo) {         setTotal(component.name, component.dots);     }); }); I'm back on track. And yes, this is for my Blades hack, Glow in the Dark. I've learned a lot from looking at your and Tim's sheet, and Chris M's Scum & Villainy sheet, but I felt like I wasn't going to learn as much if I just start swapping out values and css properties.