30

我一直在研究CoffeeScript,但我不明白您将如何编写这样的代码。它如何处理其语法中的嵌套匿名函数?

;(function($) {
          var app = $.sammy(function() {

            this.get('#/', function() {
              $('#main').text('');
            });

            this.get('#/test', function() {
              $('#main').text('Hello World');
            });

          });

          $(function() {
            app.run()
          });
        })(jQuery);
4

3 回答 3

44

实际上并没有编译它,但这应该可以

(($) ->
  app = $.sammy ->

    this.get '#/', ->
      $('#main').text '' 

    this.get '#/test', ->
      $('#main').text 'Hello World'

  $(->
    app.run()
  )
)(jQuery);
于 2010-11-12T16:03:48.780 回答
35

马特的回答是正确的,但这里有另一种方法:

在 CoffeeScript 1.0(在这个问题提出几周后发布)中,do引入了一个运算符来运行紧随其后的函数。它主要用于捕获循环中的变量,因为

for x in arr
  do (x) ->
    setTimeout (-> console.log x), 50

(将引用传递给x匿名函数)的行为不同于

for x in arr
  setTimeout (-> console.log x), 50

后者将简单地arr重复输出最后一个条目,因为只有一个x.

无论如何,你应该知道do作为一种运行匿名函数的方法,不需要额外的括号,尽管它在参数传递方面的能力目前有点有限。我已经提出了扩大它们的建议。

目前,相当于您的代码示例

do ->
  $ = jQuery
  ...

如果我的提议被接受,就可以写

do ($ = jQuery) ->
  ...

反而。

于 2011-03-06T02:54:45.250 回答
4

短变体

do ($=jQuery)->
 app = $.sammy ->
   @get '#/', -> $("#main").text ''
   @get '#/test', -> $('#main').text 'Hello world'
 $ -> app.run()
于 2013-02-06T11:21:01.737 回答