Coffeescript:同一页面上有多个Select2字段

Coffeescript:同一页面上有多个Select2字段,coffeescript,select2-rails,Coffeescript,Select2 Rails,我正在尝试使用coffee脚本使多个Select2标记字段在同一页面上工作,但失败:( 我从这个开始 $(document).on "ready page:load",( -> $("#text_field_1").select2 tags: ["A", "B", "C"] -> $("#text_field_2").select2 tags: ["1", "2", "3"] ) 没有欢乐:( 我现在让它像这样工作 text_field_

我正在尝试使用coffee脚本使多个Select2标记字段在同一页面上工作,但失败:(

我从这个开始

$(document).on "ready page:load",(
  ->  $("#text_field_1").select2
        tags: ["A", "B", "C"]
  ->  $("#text_field_2").select2
        tags: ["1", "2", "3"]
)
没有欢乐:( 我现在让它像这样工作

text_field_1 = ->
  $("#text_field_1").select2
    tags: ["A", "B", "C"]
text_field_2 = ->
  $("#text_field_2").select2
    tags: ["1", "2", "3"]

$(document).ready(text_field_1)
$(document).on('page:load', text_field_1)
$(document).ready(text_field_2)
$(document).on('page:load', text_field_2)

但这并不是一个很好的解决方案。有人能提供任何替代方案或告诉我我做错了什么吗?

您没有正确使用
->
。您只是将每一行包装在一个从未调用过的匿名函数中,然后传递两行

您只需要一个,直接传递到
$(文档)。准备就绪

$(document).ready ->
  $("#text_field_1").select2
    tags: ["A", "B", "C"]
  $("#text_field_2").select2
    tags: ["1", "2", "3"]

这是基于米格尔的建议。我发布的评论格式不太好,所以再次出现在这里

text_field_1 = ->
  $("#text_field_1").select2
    tags: ["A", "B", "C"]
text_field_2 = ->
  $("#text_field_2").select2
    tags: ["1", "2", "3"]

$(document).ready ->
  text_field_1()
  text_field_2()
$(document).on 'page:load', ->
  text_field_1()
  text_field_2()

谢谢

,但是根据TurboLink的设置,可能需要
页面:加载
的内容。谢谢meagar,我也需要页面:加载的内容,所以我使用了以下内容;
text\u field\u 1=->$(“#text\u field\u 1”)。选择2个标签:[“A”、“B”、“C”]text\u field\u 2=->$(“#text\u field\u 2”)。选择2个标签:[“1”、“2”、“2”、“3”$(文档).ready->text\u field\u 1 text\u field\u 2$(文档)。在“页面:加载”上->text\u field\u 1 text\u field\u 2
再次感谢Neil