2012-02-29 53 views
0

我在一個SimpleModal對話框中有一個Rails 3 AJAX表單,每次提交時它都會向表中添加一行。我使用了不顯眼的jquery-ujs方法。到目前爲止:Rails 3 + SimpleModal + AJAX:提交按鈕只能工作一次

  • 如果不在對話框中,AJAX表單可以工作多次。

  • 如果它位於SimpleModal對話框中,它只能使用一次。之後,提交按鈕停止工作。沒有提交,沒有錯誤,沒有任何東西,雖然它從js控制檯手動提交時工作正常,即$('...')。submit();

感覺就像一個事件處理程序被刪除時SimpleModal移動HTML來一個對話框,但一切都在jquery-ujs source看起來像一個.delegate()方法,所以我不知道爲什麼它不會得到重新連接。

我懷疑有一個非常簡單的解決方案,我只是沒有意識到,解決了大約20個字符的問題。

下面是相關代碼:

頁JS(應用程序/資產/ Java腳本/ binders.js):

$(function() { 

    // Hide the form initially: 
    $('#add_binder_modal').hide(); 

    // Show as SimpleModal when add link clicked: 
    $('#add_binder_link').click(function(event) { 
    event.preventDefault(); 
    $('#add_binder_modal').modal(); 
    }); 

    // Close on success: 
    $("form").bind("ajax:success", function(xhr, data, status){ 
    $.modal.close(); 
    }); 
}); 

這裏是我的Rails形式(應用程序/視圖/粘合劑/ _form.js):

#add_binder_modal.container 
    = form_for Binder.new, :remote=>true do |f| 
    = f.text_field :subject 
    = f.submit 

我不認爲你需要它,但爲了以防萬一,這裏的控制器(應用程序/控制器/ binders_controller.rb):

class BindersController < ApplicationController 
    respond_to :html, :js 

    def create 
    @binder = Binder.new(params[:binder]) 
    @binder.save 

    respond_to do |format| 
     format.html { redirect_to binders_path } 
     format.js 
    end 
    end 

end 

最後,它與(應用程序/視圖/粘合劑/ create.js.erb)響應的JS:

$('<%= escape_javascript(render(:partial => 'show', :locals=>{:binder=>@binder}))%>') 
    .appendTo('.binders .atable tbody').hide().fadeIn(); 

回答

0

我最後不得不挖入simplemodal JavaScript源比特。沒有魔法彈。這只是調試和追蹤發生的事情。

0

在有可能以快速的刺(沒有更徹底地瞭解你在做什麼):考慮是否需要使用.live(...)方法而不是.click(...)。或者說,.on()或.delegate()取決於您使用的jQuery版本。

http://api.jquery.com/live/

http://api.jquery.com/on/

http://api.jquery.com/delegate/

+0

謝謝。我知道這是一個晦澀的問題。不知道會做到這一點。 'click'事件在打開對話框的鏈接上,所以它不會在任何地方發生。這是對話框中的按鈕被轉移並且無法執行。 – Ricky 2012-02-29 22:57:13