【问题标题】:Ruby on rails cocoon gem - unable to capture callback eventsRuby on rails cocoon gem - 无法捕获回调事件
【发布时间】:2017-02-07 01:51:16
【问题描述】:

您好,我目前正在为我的 rails 应用程序使用 cocoon gem,它似乎工作正常,因为我能够在表单中添加和删除嵌套关联。但是,当我尝试控制台记录回调(例如“cocoon:after-insert”)时,控制台上没有触发控制台日志。这可能是什么原因,我如何在控制台中捕获回调事件?我的应用程序中也捆绑了 gem remotipart,如果这可以提供任何线索说明为什么我无法在控制台上捕获回调。她是我的密码:-

#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');
    });
});

【问题讨论】:

  • 尝试将 js 代码移动到部分

标签: jquery ruby-on-rails cocoon-gem


【解决方案1】:

您必须确保在周围的 div 上捕获事件。你也不需要 turbolinks 代码,你可以简单地做类似的事情

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

简而言之:监听整个文档中的事件,如果我们捕捉到cocoon:after-insert 事件,我们会从.content form 记录一些内容。

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多