2012-01-26 48 views
8

我正在將舊rails應用升級到3.1。該應用程序非常有用,但我需要更新一些ajax功能。 (如果它有什麼區別,我正在使用jQuery和coffeescript)Rails升級到3.1 - 將ajax處理從「render:update」更改爲respond_to

所有現有的ajax功能都是使用render:updates編寫的。例如

render :update do |page| 
    page.remove "financial_tran_offset_#{params[:ftof_id]}" 
    page.replace_html 'details', :partial => 'details', :locals => {:obj => @fire} 
end 

我認爲這樣做的新的首選方法是使用respond_to?阻止處理js,但我不確定處理這些不同情況的最佳方式。

對於第一種情況(page.remove),我認爲使用資產管道線,我應該有一個外部js in/app/assets/javascripts /來處理javascript方面(例如page.remove),但我是不知道如何將參數傳遞給js文件。我猜你可以做這樣的事情:

respond_to do |format| 
    format.js {:render :js => {:ftof => params[:ftof_id]} 
end 

但我不知道你怎麼可以從js文件中選擇這個。這是正確的方式將信息傳遞給js嗎?還是有另一種方法我應該使用?

對於第二種情況(page.replace_html),我認爲這已從3.1(根據apidock)已被棄用/刪除。我懷疑這應該是使用應用程序/資產/ JavaScript目錄中的js文件,但不知道如何去渲染部分並將這些信息傳遞給js。

感謝在這方面的任何指針=)

回答

31

使用jQuery與js.erb視圖和respond_to塊結合。

不管這個動作是(我們會說FoosController#update例如着想):

render :update do |page| 
    page.remove "financial_tran_offset_#{params[:ftof_id]}" 
    page.replace_html 'details', :partial => 'details', :locals => {:obj => @fire} 
end 

將成爲:

respond_to do |format| 
    format.html 
    format.js  # <- this is what we're after 
end 

以查看文件update.js.erb

$('#financial_tran_offset_<%= params[:ftof_id] %>').remove(); 
$('#details').replaceWith('<%= escape_javascript(render(:partial => 'details', :locals => {:obj => @fire})) %>'); 

update.js.erb將被ERb解析,呈現爲JS,發回給客戶t通過Ajax和eval'd。

你可以傳遞任何你想要的JS模板。畢竟,它們是ERb文件。像使用HTML/ERb視圖一樣使用<%= %>和實例變量。如果您在JS/ERb視圖中調用render,請用escape_javascript包裝它以使HTML正確呈現。


render :update呼籲原型老JavaScriptGenerator輔助方法。轉換爲jQuery非常簡單,因爲它們都做同樣的事情:選擇一個DOM元素並對其進行操作。

這裏有一個很好的小翻譯表,帶有典型的操作。從控制器原型的輔助方法,並把他們的jQuery或JS對應於相應的JS/ERb的觀點:

 Prototype       jQuery/Javascript 
    in controller     in JS/ERb view (xxxxxx.js.erb) 
     ---------       ----------------- 
page.alert "message"     alert('message'); 
page.hide "id"      $('#id').hide(); 
page.insert_html \ 
     :top, "id", "content" $('#id').prepend('content'); 
     :bottom, "id", "content" $('#id').append('content'); 
     :before, "id", "content" $('#id').before('content'); 
     :after, "id", "content" $('#id').after('content'); 
page.redirect_to "url"    window.location.href = 'url'; 
page.reload       window.location.reload(); 
page.remove "id"      $('#id').remove(); 
page.replace "id", "content"   $('#id').replaceWith('content'); 
page.replace_html "id", "content" $('#id').html('content'); 
page.show "id"      $('#id').show(); 
page.toggle "id"      $('#id').toggle(); 

不要忘記你的每一條線路分號!

+0

很酷。無論如何用coffeescript來做到這一點,或者你是否僅限於update.js.erb中的直接js? –

+0

如果你真的想要使用CoffeeScript,你可能可以,但動態視圖支持是我看不出來的。 (我個人更喜歡直JS。)用於簡單jQuery單行程序的CoffeeScript有點矯枉過正。 $('#id')。append('content');'到'$('#id')。append'content''。保存一組括號不值得花費。 JQuery非常簡潔且足夠簡單。不妨堅持下去。 – Substantial

+0

非常詳細的答案,謝謝! –