简体   繁体   中英

Rails 4, Turbolink execute javascript after render a partial

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

//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.

//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.

The modal is a classic Twitter Bootstrap modal:

//_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>

Try:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM