2013-05-21 27 views
4

爲了簡單起見,我有一個表單來更新部分。沒有什麼特別的。在部分內容中,我有一個jQuery可排序列表。在更新表單之前,我可以毫無問題地在列表中拖動它。Rails - 爲什麼jQuery不能在遠程提交我的表單後加載

但是,我更新列表後,這就像js不重新加載,我不得不刷新整個頁面,讓事情再次滾動。

我試過了所有的東西,甚至借用了demo jQuery application from Ryan Bates Esq. over here.這個功能在我放了部分js shizzle之後不起作用。

我敢肯定這很簡單,但我是一個ajax/jQuery新手,我真的很掙扎。

查看:

#test_one 
    = render "test_one" 

部分 「test_one」

= form_for @location, :remote => true do |f| 
    %table 
    %tr= collection_select(:location, :type_ids, Type.all, :id, :name, {:prompt => true}, :multiple => true, :class=>"chzn-select") 
    %tr 
     %td 
     %ul#types.unstyled{"data-update-url" => sort_types_locations_url} 
      - @types.each do |type| 
      = content_tag_for :li, type do 
       %span.handle 
       [Drag] 
       = type.name 

update.js.erb

$("#test_one").html('<%= escape_javascript render("test_two") %>'); 

而且在我的控制器:

def update 
    @location = Location.find(params[:id]) 
    @types = @location.types.order('location_types.position').limit(2) 
    respond_to do |format| 
     if @location.update_attributes!(params[:location]) 
     flash[:notice] = 'Settings updated successfully' 
     format.html { redirect_to edit_location_path } 
     format.js 
     else 
     format.html { render action: "edit_access" } 
     format.js { render action: "update_access_errors" } 
     end 
    end 
    end 

最後在locations.js.coffee

jQuery -> 
    $('#types').sortable(
     axis: 'y' 
     update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize')) 
    ) 

的更新工作,我沒有得到任何錯誤,我沒有在我的控制檯。現在我有很多輸了 - 我更新記錄後如何讓js重新加載?

回答

5

原因是,您的自定義js(關於可排序)已加載到文檔準備就緒,並且在部分更新後不會再次被觸發。

解決方案是:將您的自定義js包裝到一個函數中。文檔準備就緒並更新時調用此函數。

# locations.js.coffee 
$ -> 
    $(document).custom_js() 

$.fn.custom_js -> 
    $('#types').sortable(
    axis: 'y' 
    update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize')) 
    ) 

# update.js.erb 
$("#test_one").html('<%= escape_javascript render("test_two") %>'); 
$(document).custom_js(); 

旁註有關自定義js函數:沒有必要在這裏包裝所有的自定義代碼,只是涉及什麼打算添加/阿賈克斯更新的一部分。

+1

你剛剛改善了我的心情和周圍其他人的心情十倍:)非常感謝。不簡單! – simonmorley

+0

@simonmorley,我很高興能有點幫助:) –

+0

@BillyChan謝謝你,我只是在想 - 當我有一個循環,其中部分呈現一百次,這意味着代碼'update.js .erb'也會被調用一百次 - 這可能會減慢應用程序的運行速度。只是想知道 - 是否有更有效的解決方案?謝謝。 – user984621

相關問題