Search code examples
arrayscoffeescriptconditional-statementsframerjs

access other values in array in coffee script in a loop (framer.js)


Hi I'm fairly new to javascript and CoffeeScript, so I'm currently working on a prototype and learning the language simultaneously.

The following block of code does almost what I want it to do except for one important thing. Any help would be greatly appreciated

categories.forEach (cat,i) ->
    mainCat= categ[i] = new Layer
     width:185
     height:77
     parent:catSelect.content
     y:13
     x:205*i+20
     image:categories[i]
   categ[i].states.add
    off:
        image: categories[i]
    on:
        image: altCat[i]
   categ[i].on Events.Click, ->
    categ[i].states.next("on","off")

    if categ[i].states.current is "on"
        print "true"

Here I have a loop to create category buttons (mainCat) which have 2 states with separate arrays of images attached (categories[] and altCat[]).

I have put this loop in an array, so that now, when i click a category, I can check its state using categ[i], but that's pretty much where my limits are.

Right now this basically treats objects in my categ[] array as a multiple choice, whereas I want it to only let one object in the array be in the "on" state at a time and, once it's in the "on" state, it needs to show a specific row of cards while keeping other rows hidden in another array (call it cards[]) located in a separate layer/div.

i.e. something like:

  if categ[!=i].states.current is "on"
   categ[!=i].states.switch("off")
   cardsRow[!=i].opacity=0
   cardsRow[i].opacity=1

Thanks in advance!


Solution

  • You have to loop over all the objects in categ to and then check if they are the same as the layer that has been clicked on, to switch them on or off.

    The same holds for setting the opacity for a layer in another array, but then you should use the index of the loop to look the layer up:

    categ[i].on Events.Click, ->
        for l, index in categ
            if categ[i] == l
                l.states.switch("on")
                cards[index].opacity = 1
            else
                l.states.switch("off")
                cards[index].opacity = 0
    

    A full prototype with this at work, can be found here: http://share.framerjs.com/2yg7ix83yv1l/ I've replaced the images by background colors to make the layers visible.