簡體   English   中英

Rails:在表單提交並綁定到dom后重新部分渲染

[英]Rails: Re-render partial after form submit and bind to dom

我知道這個問題已經被要求並重新提出,但是我無法確定。

我有一個視圖,從局部渲染一個表單

.myform
  = render "someform"

這是表格

= simple_form @object, remote: true do |f|
  = f.input :field1
  = f.input :name, as: :autocomplete
  = f.submit

沒有在控制器中進行任何精美的渲染,它只是在使用remote: true提交表單時渲染js視圖remote: true

因此它稱為object.js.haml

:plain
  $("form.new_object").html("#{escape_javascript(render(:partial => '/objects/someform'))}");

本質上,我只是將表單替換為new對象。

麻煩的是,您的JS-heads將會看到我要使用的方法,它不再與DOM綁定,這意味着其他javascript事件沒有觸發,在這種情況下,是typeahead(這使用的是稱為自動完成)。

因此,如何重新渲染someform部分,並確保新輸入與js typeahead事件相關聯?

在這個瘋狂而瘋狂的POST ajax世界中處理綁定事件處理程序的一種方法是使用委托事件。

整個想法不是將處理程序添加到委派給容器甚至文檔本身的每個小元素上。

 $('#add').click(function(){ $("#playground").append("<button>Test me too!</button>") }); // This will only fire when you click the button that was present // when the handlers where bound $("#playground button").click(function(){ console.log("I'm bound to an element!"); }); // This trickles down to every element that matches the selector $("#playground").on('click', 'button', function(){ console.log("I'm delegated!"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="playground"> <button>Test</button> </div> <button id="add">Add a new button</button> 

但是由於typeahead不允許您以這種方式委托,因此您可以做的是在將元素附加到DOM之前附加typeahead處理程序。

var obj = $("#{escape_javascript(render(:partial => '/objects/someform'))}");
obj.find('.typeahead').typeahead({
 // ...
});

$("form.new_object");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM