Ruby on rails cocoon gem - unable to capture callback events

隐身守侯 提交于 2020-01-24 21:35:08

问题


Hi I am currently using the cocoon gem for my rails app and it seems to be working fine since I was able to add and remove the nested associations in my form. However, when I try to console log the callbacks (e.g. "cocoon:after-insert"), there is no console log fired on the console. What could be the reason for this and how can i capture the callback event in my console? I have the gem remotipart bundled in my app too, if this would offer any clue as to why I have been unable to capture the callbacks on my console. Her are my codes:-

#new.html.erb
<div class="content">
  <%= form_for [@strategy,@goal], :html => {:class => 'ui form'}, :remote => true do |f| %>
    <p>
      <%= f.label :title %>
      <%= f.text_field :name %>
    </p>

    <div id = 'tactical_field'>
      <%= f.fields_for :tactics do |tactic| %>
        <%= render 'tactic_fields', f: tactic %>
      <% end %>
    <div class="links">
      <%= link_to_add_association "Add", f, :tactics %>
    </div>
    </div>
    <p>
      <%= f.button :submit => "", class: "ui button" %>
    </p>
  <% end %>
</div>

#_tactics_fields.html.erb
<div class="nested-fields">

  <div class='field'>
    <%= f.label :tactic %>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :rating %>
    <%= f.text_field :rating %>
  </div>
  <%= link_to_remove_association "delete", f %>
</div>

# application.js
$(document).on('turbolinks:load', function() {
  $('#tactical_field').bind('cocoon:before-insert', function() {
     console.log('helloworld');
    });
});

回答1:


You have to make sure the event is captured on a surrounding div. Also you do not need the turbolinks code, you can simply do something like

$(document).on('cocoon:after-insert', '.content form', function(e) {
  console.log('Something'); 
});

So in short: listen to events on the complete document, if we capture a cocoon:after-insert event, from .content form we log something.



来源:https://stackoverflow.com/questions/42080359/ruby-on-rails-cocoon-gem-unable-to-capture-callback-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!