アプリなどを開発するブログ

React Native / Swift / Ruby on Railsなどの学習メモ。


【jQuey + CoffeeScript】forループ内でclickイベントを設定

jQueryで動的にボタンを3個生成し、
それぞれをクリックすると、テキストフィールドにそれぞれの値が入る機能の実装。

普通に何も考えないでやるとこんな感じに書いてしまってました。

  test_locations = [{ name: 'test1' }, {name: 'test2'}, {name: 'test3'}]
  listupLocations(test_locations)

  listupLocations = (locations) ->
    return if locations.length <= 0
    location_names = []
    for location, index in locations
      btn = $("<div id='btn#{index}'>#{location.name}</div>")
      $('#place_names_block').append(btn)
      btn.click ->
        selected = $(this).text()
        $('#place_name').val(selected)

しかしこれだと変数が上書きされてしまって思うように動きません。
こんな感じにしたら意図通り動いた。

  test_locations = [{ name: 'test1' }, {name: 'test2'}, {name: 'test3'}]
  listupLocations(test_locations)

  listupLocations = (locations) ->
    return if locations.length <= 0
    location_names = []
    for location, index in locations
      $('#place_names_block').append("<div id='btn#{index}'>#{location.name}</div>")
      $('#btn'+index).click ->
        selected = $(this).text()
        $('#place_name').val(selected)

こういう解決方法もあるみたいです。 Closures - JavaScript | MDN