如何在 coffeescript 中编写文字 jQuery 对象

How to write literal jQuery object in coffeescript

本文关键字:文字 jQuery 对象 coffeescript      更新时间:2023-09-26

我正在尝试将一些代码转换为coffeescript,但我遇到了问题:

var $el = $('<span/>', {
    class : 'myclass',
    click : function () {
        var $this = $(this)
        if (foo) { // radio & check
            baz($this)
        }else{
            bla($this)
        }
    }
});

我在咖啡里是这样写的:

$el = $('<span/>',
  class: 'myclass'
  click: ->
    $this = $(this)
    if foo
      baz $this
    else
      bla $this
)

这工作得很好,但我真的很不喜欢最后一个括号,有什么办法可以编写没有参数的代码,只是缩进?

如果去掉两个括号,工作正常。

$el = $ "<span/>",
  class: "myclass"
  click: ->
    $this = $(this)
    if foo
      baz $this
    else
      bla $this

另请参阅:http://js2coffee.org/