Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to loop over each in coffeescript?

I'm trying to programmatically create some javascript buttons to toggle visibility on the page (for snappy tag filtering). This works for one tag:

trigger = ".sales-focus-btn"
target = ".sales-focus"

jQuery ->   
  $(trigger).toggle ->
    $("#primary-content").find('.container').hide()
    $("#primary-content").find(target).show()
  , ->
    $("#primary-content").find('.container').show()

Is it possible to do something similar in coffeescript, but with arrays, e.g.

trigger = [
  ".sales-focus-btn"
  ".service-focus-btn"
  ".other-focus-btn"
  ...
]
target = [
  ...
]

Is it possible to loop over and create a toggle for each type of tag?

UPDATE

Yes it's possible. Use the form:

myFunction = (el) -> console.log el
myFunction elem for elem in array
like image 740
Tyler Avatar asked Jul 07 '12 01:07

Tyler


1 Answers

Of course it's possible:

content = $('#primary-content')
container = content.find('.container')

tags = [
    '.sales-focus'
    '.service-focus'
    '.other-focus'
]

$.each tags, (tag) ->
    target = content.find(tag)
    $(tag + "-btn").toggle ->
        container.hide()
        target.show()
    , ->
        container.show()

Remember to cache your DOM elements. Alternatively use for tag in tags instead of jQuery.each tags, (tag) -> ...:

for tag in tags
    do ->
      target = content.find(tag)
      $(tag + "-btn").toggle ->
        container.hide()
        target.show()
      , ->
        container.show()

(the do -> IIFE is necessary to keep each target in scope, as @epidemian pointed out)

like image 159
Ricardo Tomasi Avatar answered Nov 10 '22 00:11

Ricardo Tomasi