javascript - 当分配另一个函数的结果时,如何使此更改事件代码在 Coffeescript 中工作?

标签 javascript jquery ruby-on-rails select coffeescript

在我的 Rails 4 应用程序中,当选择下拉选项发生更改时,我尝试更改编辑表单上的三个文本字段。使用 CoffeeScript 1.7.1/Rails 4.0.2/Ruby 2.1.0。

我的 Coffeescript 文件:

$(document).ready ->

    new_item = (items_array, item) ->
        for si of items_array
            if items_array[si][3] is item
                new_studio_item = items_array[si]
                return new_studio_item

    $('#pk_item_studio_item_id').change ->
        old_item = $('#pk_item_starting_item').val()
        studio_item = $('#pk_item_studio_item_id').val()
        unless old_item == studio_item
            studio_items = $('#pk_item_studio_items').val()
            [name, description, price, id] = new_item studio_items, studio_item
            document.getElementById("pk_item_custom_name").value = name
            document.getElementById("pk_item_custom_description").value = description
            document.getElementById("pk_item_lab_price").value = price
            return

此行上的“new_item”函数没有分配任何内容:

[name, description, price, id] = new_item studio_items, studio_item

然而,在coffee的REPL中,这一行确实返回namedescriptionpriceid的值。我尝试过 Firefox、Chrome 和 Safari,并得到相同的结果:文本字段值保持不变。

希望我的代码有明显的错误。我需要改变什么想法吗?如有必要,我很乐意提供更多代码详细信息( View / Controller /等),只是不想将其变成不必要的 TLDR。

更新:此代码将我的数组返回到测试字段中的表单:

    ready = ->

        $('#pk_item_studio_item_id').change ->
            old_item = $('#pk_item_starting_item').val()
            studio_item = $('#pk_item_studio_item_id').val()
            unless old_item == studio_item
                studio_items = $('#pk_item_studio_items').val()
                document.getElementById("test_input").value = studio_items
                return

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

这是返回的数组:

[["项目 0 的自定义名称", "项目 0 的自定义描述", "1.1", 1], ["项目 1 的自定义名称", "项目 1 的自定义描述", "1.1 ", 2], ...(等等,等等)..., ["项目 39 的自定义名称", "项目 39 的自定义描述", "1.1", 40]]

但是当 new_item 函数(参见上面的第一个代码块)被编码为通过将最后一行更改为 return items_array 返回 items_array 时,我得到 ,,,,,,,,,,,,,,, (etc.) 返回,而不是与上面相同的数组。因此,我在将数组发送到函数的方式或函数处理数组的方式上做错了。

最佳答案

$(document).ready -> 替换为 jQuery ->,这是正确的 CoffeeScript 语法

关于javascript - 当分配另一个函数的结果时,如何使此更改事件代码在 Coffeescript 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541464/

相关文章:

javascript - jquery - 使用图像的 attr() 时未定义 src

jquery - 我需要像选项卡菜单栏一样在图像之间切换

javascript - Javascript 中将文本框限制为小数点后两位

ruby-on-rails - Assets 文件夹中没有路线与 [GET] 文件匹配

ruby-on-rails - Ruby 和 Golang 时间解析

javascript - 参数类型 '__0' 和 'value' 不兼容 - Typescript

javascript - Node.js 中的计时器有何特殊之处?

javascript - 在 ExpressJS 中向文件路径添加参数

jquery - 错误: jQuery . ..未被调用——Ajax从Node.js跨域服务器请求geoJSON

ruby-on-rails - rake 命名空间与 ruby​​ 模块