2015-07-10 59 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

相關問題