Rails 4, Turbolink在呈现部分后执行javascript

时间:2022-10-08 16:37:22

I have a form configured with some javascript. The javascript is loaded on load event handled by Turbolink:

我有一个配置了一些javascript的表单。使用Turbolink处理的加载事件加载javascript:

//app/assets/javascripts/init.js
var ready = function () {
    App.init(); //I configure some components of _form.html.erb partial
};
$(document).ready(ready);
$(document).on('page:load', ready);

If I render a partial the App.init() code is not execute and my application is not well configured.

如果我呈现一个部分,那么App.init()代码没有执行,并且我的应用程序配置不佳。

//new.js.erb
$("#my-modal").html("<%= j( render 'form') %>");
$("#my-modal").modal("show"); //The partial is inside a modal

Can I execute the code after the partial is rendered? Something like this:

我能在呈现部分后执行代码吗?是这样的:

$(document).on('partial:render', ready); //Concept

In need to execute the js code after the partial is render becouse I need to configure some Jquery plugin to customize the modal form.

需要在呈现部分后执行js代码,因为我需要配置一些Jquery插件来定制模态表单。

The modal is a classic Twitter Bootstrap modal:

模式是一个经典的Twitter引导模式:

//_form.html.erb
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      <div class="row">
        <div class="col-sm-offset-3 col-sm-9">
          <h3 class="modal-title" id="myModalLabel">new</h3>
        </div>
      </div>
    </div>

    <%= simple_form_for(...) do |f| %>
        <div class="modal-body">
          <ul class="errors"></ul>
          <%= f.error_notification %>

          <%= render "companies/fields", f: f %>
          ...
          ...
        </div>
    <% end %>
  </div>
</div>

1 个解决方案

#1


2  

Try:

试一试:

$(document).on('page:change', function () {
  // Actions to do
});

In your case simpley replacing the 'page:load' line in your js call with:

在您的例子中,simpley将js调用中的“page:load”行替换为:

$(document).on('page:change', ready);

#1


2  

Try:

试一试:

$(document).on('page:change', function () {
  // Actions to do
});

In your case simpley replacing the 'page:load' line in your js call with:

在您的例子中,simpley将js调用中的“page:load”行替换为:

$(document).on('page:change', ready);