This is a read-only archive of the Framer Community on Facebook.

What is Framer? Join the Community
Return to index
Israel Gonzales
Posted Nov 15 - Read on Facebook

Sup dudes, super simple question but for some reason I can't figure it out. Basically, I'm trying to associate two arrays such that each layer in one array changes the behavior in the other array.

I keep getting errors when I want to reference items in the second array. Generally, I'm looking for best practices on this type of behavior as it's a pretty common pattern.

4 Comments

Ban Nguyen

Maybe the space?

Joseph Reni

I've run into this before - the function inside of the on click only reads the last iteration of the loop so i = 3 and it just breaks. I solved it in a class by using @variable but I'm not sure about this case specifically, I'm not that smart.

Kevin Mao

This is a scope problem like Joseph mentioned. You can use "do" to "capture" the variable i, like Framer says in their guides (https://framer.com/getstarted/guides/programming/#scope). Not sure what that means tho 😂

Alan Travis

Let me take a stab at explaining "do" and "capturing the variable"... I may go to deep into code space, but I'm going to try explaining it.

To assist I've attached a screenshot of decaffeinated coffeescript :) [yes that is a thing]

In the picture you see the 2 versions of the for loop on the left... with their vanilla javascript on the right.

The first one (which doesn't work as you would expect) declares variable i, and then uses that ONE instance of i when referencing each of the array elements of blues[]... But it then also uses that same instance of i inside the onClick function... The problem is that there is only ONE instance of i that all 3 of the blue boxes are using to know what index to use within the reds[] array... The problem get's worse when you realize that i increments to 3 in order to break out of the for loop, which is why you get the error about reds[i].stateCycle()... reds[3] doesn't exist.

The difference in the 2nd function, the one with do(i) -> is that in addition to declaring the i variable by the for loop, a NEW i is created for each of the 'do' function calls... This is the 'capture' part, and also the Scope part mentioned by others... do is creating for us what's referred to as an IIFE (Immediately-Invoked Function Expression)... Couple that with the fact that in Javascript variables are scoped to their containing function, and we have all the pieces to 'capturing the variable'

it's the IIFE that captures the variable, and creates a new instance of the variable... And then protects/maintains that unique copy of the variable because it is contained within the scope of the IIFE itself.

Read the entire post on Facebook