4

簡単にするために、パーシャルを更新するフォームを用意しました。特別なことは何もありません。パーシャル内には、jQuery の並べ替え可能なリストがあります。フォームを更新する前に、問題なくリスト内をドラッグできます。

ただし、リストを更新した後、js が再読み込みされていないようで、ページ全体を更新して元に戻す必要があります。

Ryan Bates Esq からデモ用の jQuery アプリケーションを借りて、あらゆることを試しました。こっち。部分的にいくつかのjsシズルを入れた後も、それは機能しません。

シンプルだと思いますが、私は 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

そして最後に location.js.coffee に

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

更新は機能し、エラーは発生せず、コンソールには何も表示されません。レコードを更新した後に js をリロードするにはどうすればよいですか?

4

1 に答える 1

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 関数に関する補足: すべてのカスタム コードをここでラップする必要はありません。Ajax によって追加/更新されるものに関連する部分だけです。

于 2013-05-21T14:25:12.980 に答える