1

我最近开始学习CoffeeScript,我遇到了这样的问题。我想写javascript:

TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions()).done(
        function(rendered) { // something1
}).fail(function(ex) {
    // something2

});

我可以通过什么方式得到它?我尝试重写:

TemplateManager.tmpl @template, @modelJSON(), @templateOptions()
    .done (rendered) ->
       #something1
    .fail (ex) ->
       #something2

我得到:

TemplateManager.tmpl(this.template, this.modelJSON(), this.templateOptions().done(function(rendered) {

  }).fail(function(ex) {

  }));
4

2 回答 2

3

tmpl为和done方法添加括号

TemplateManager.tmpl( @template, @modelJSON(), @templateOptions() )
   .done( (rendered) -> 
        #something1 
    )
   .fail (ex) ->
        #something2

解决方案并不优雅,我认为其他人可能会在咖啡脚本中提供更好的方法

更新

基于评论,删除括号done。我已经更新了代码,我认为这个很优雅

TemplateManager
   .tmpl(@template, @modelJSON(), @templateOptions())
   .done (rendered) -> 
        some
        code
        here 

   .fail (ex) ->
        another
        code
        here
于 2013-03-19T08:24:01.870 回答
2

不要把“我不使用括号,因为它们是可选的”和棘手的难以理解的缩进弄得一团糟,而是把东西分成小块,给这些块命名,然后简单地把它们放在一起:

done = (rendered) ->
    # something1
fail = (ex) ->
    # something2
TemplateManager.tmpl(@template, @modelJSON(), @templateOptions())
    .done(done)
    .fail(fail)

我不知道“something1”和“something2”是什么,所以我不能给他们合适的合理名称,考虑donefail作为概念名称的证明。

仅仅因为一个函数可以是匿名的并不意味着它必须是匿名的,仅仅因为一些括号是可选的并不意味着它们必须被省略。

于 2013-03-19T08:36:24.480 回答