Javascript 有没有一种方法可以在CoffeeScript中向这个JQuery调用添加另一个函数引用参数,而不必为每个参数使用一行?

Javascript 有没有一种方法可以在CoffeeScript中向这个JQuery调用添加另一个函数引用参数,而不必为每个参数使用一行?,javascript,jquery,syntax,coffeescript,Javascript,Jquery,Syntax,Coffeescript,是否有方法将错误:参数添加到此行,而不使用每行一个参数的格式 $.ajax type:'DELETE', url: '/history', data: {id: id}, success: (data)-> $('#row'+index).detach() 我知道我能把它变成 $.ajax type: 'DELETE' url: '/history' data: id: id success: (data) -> $('#row' + index).de

是否有方法将
错误:
参数添加到此行,而不使用每行一个参数的格式

$.ajax type:'DELETE', url: '/history', data: {id: id}, success: (data)->
  $('#row'+index).detach()
我知道我能把它变成

$.ajax
  type: 'DELETE'
  url: '/history'
  data: id: id
  success: (data) ->
    $('#row' + index).detach()
  error: ->
    alert 'Error'
但我想尝试学习更多复杂的咖啡脚本语法。我知道我可以在
$.post
中使用括号,但这允许链接回调,这与此
$.ajax
格式不同

$.post("/history", {food: food, size: size, unit: unit}, (data)->
  alert 'Success'
).fail ->
  alert 'Fail'
我尝试了以下操作,但它从未调用成功回调:

$.ajax type:'DELETE', url: '/history', data: {id: id}, 
  success: (data)->
    alert 'Success'
    $('#row'+index).detach()
  error: ->
    alert "Could not delete the food."

这成功了

$.ajax type:'DELETE', url: '/history', data: {id: id}, success: ((data)->
  $('#row'+tmpIndex).detach()
), error: ->
  alert "Could not delete the food."

你的例子编译成

$.ajax({
  type: 'DELETE',
  url: '/history',
  data: {
    id: id
  }
}, {
  success: function(data) {
    alert('Success');
    return $('#row' + index).detach();
  },
  error: function() {
    return alert("Could not delete the food.");
  }
});
你可以这样做

$.ajax type:'DELETE', url: '/history', data: {id: id}
  ,success: (data) ->
    alert 'Success'
    $('#row'+index).detach()
  ,error: ->
    alert "Could not delete the food."
……但我认为这不是一个好的做法

如果您的目标是了解coffeescript的工作原理,我建议您在网站上使用live解析器,例如:


旁注:所有jqueryajax函数(post/get/ajax)都返回承诺,这比通常的回调有很多好处。这里有更多相关内容:

如果你喜欢编写难以理解的代码,而这些代码会让那些在维护代码时陷入极度仇恨的人满腹怨恨,你可以添加括号:

$.ajax type:'DELETE', url: '/history', data: {id: id}, success: ((data)-> ...), error: (-> ...)
但请不要这样做。最好使用多行版本或使用命名函数:

success = (data) ->
    # ...
error = ->
    # ...
$.ajax type:'DELETE', url: '/history', data: {id: id}, success: success, error: error

我更喜欢避免使用长度超过几行的匿名函数。无论如何,缩进很快就会变得混乱。

我不知道coffeescript,但我敢打赌,在成功函数和
错误之间需要一个逗号:
我不喜欢浪费换行符。但我确实喜欢命名函数!但我不喜欢一行命名的函数,但滚动需要时间。我会把显示器垂直翻转。(过去有过。)奇怪的是,HAML&Ruby需要标点符号
&&
,在行尾,而CoffeeScript需要标点符号。