2015-07-10 56 views
0

有没有一种方法可以将error:参数添加到此行中而不使用每行格式的单个参数?有没有办法在CoffeeScript中为这个JQuery调用添加另一个函数引用参数,而不用为每个参数使用一行?

$.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' 

但我想尝试学习更多的CoffeeScript语法的复杂的。我知道我可以使用括号作为$.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." 
+0

我不知道CoffeeScript的,但我敢打赌,你需要成功的功能和'误差之间的逗号:' – Barmar

回答

1

如果您在编写代码难以理解,将填补谁卡住保持与燃烧的仇恨你的代码的喜悦,你可以只添加括号:

$.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 

我宁愿避免比反正两线较长的匿名函数,缩进被混淆非常快。

+0

我不喜欢浪费换行。但我喜欢命名的功能!但我不喜欢1行命名函数。 – Chloe

+0

但换行符是免费的,使代码更具可读性。 –

+0

但滚动花费时间。如果会的话,我会将显示器垂直翻转。 (在过去。) – Chloe

1

你的榜样编译成...

$.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的作品,我建议与网站例如在现场解析器打转转:http://coffeescript.org/#try

旁注:所有的jQuery AJAX功能(后/获取/ AJAX)的回报承诺,它比通常的回调有很多好处。更多关于这里:https://gist.github.com/domenic/3889970

+0

这很奇怪的是HAML和红宝石需要的标点''或''&&在的结束行,但CoffeeScript在开始时需要它。 – Chloe

相关问题