Jake Schievink
Jake Schievink

Reputation: 409

Easy way to toggle something without global variables

I feel bad for asking this as it is a very easy question. I want the cycleBackground function to alternate between changeBackground("#firstbg", img.src) and changeBackground("#secondbg", img.src)

    cycleBackground = ()->
        img = new Image()
        img.src = '/assets/'+Math.floor(Math.random()*50)+'.jpg)'
        img.onLoad = ()->
            changeBackground("#firstbg", img.src)

I was about to create a global var called "selected" and make it equal "#firstbg" and if selected is "#firstbg" then change it to "#secondbg" so that everytime cycleBackground is called it changes the background of whichever element hasn't already been changed. I know this is bad coding practice, what would be a better solution?

Upvotes: 0

Views: 144

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61530

You could introduce a variable x that holds what image you are looking at currently, and do something like this:

x = 0; 
img.onLoad = ()->
   x = Math.abs(x-1); # toggle
   changeBackground("#" + ['firstbg','secondbg'][x], img.src);

Note: I don't know where x would live because I know absolutely nothing about CoffeeScript.

Upvotes: 0

user229044
user229044

Reputation: 239402

Just create a new variable in the same scope as your function; either cycleBackground or changeBackground, whichever. This is completely fine. CoffeeScript wraps the entire compiled file in an IIFE and doesn't introduce any global variable unless you explicitly attach them to the global object (window.selected = ... for example).

selected = 'first'

cycleBackground = ()->
  img = new Image()
  img.src = '/assets/'+Math.floor(Math.random()*50)+'.jpg)'
  img.onLoad = ()->
    selected = (if selected == 'first' then 'second' else 'first')
    changeBackground("##{selected}bg", img.src)

Upvotes: 2

Related Questions