问题
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