没有涡轮链接的AJAX之后在rails中触发js [英] firing js in rails after AJAX with no turbolinks

查看:49
本文介绍了没有涡轮链接的AJAX之后在rails中触发js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails4应用程序.由于我不太擅长js,因此我关闭了TURBOLINKS.我已经阅读了很多文章,但仍然无法弄清楚如何组织我的javascript文件.目前,我在AJAX追加后触发js代码时遇到问题.

I have a rails4 app. Since I'm not good at js yet I TURNED OFF TURBOLINKS. I have read a bunch of articles, still I couldn't figure it out how to organize my javascript files. At the moment I have a problem with firing js code after AJAX append.

我有一个任务列表(索引页).如果我加载页面,那么我可以单击任何任务(以更新它们),并且引导程序模式会显示+以下代码正在运行,因此时间已格式化,并且datetimepicker可用.

I have a list of tasks (index page). If I load the page then I can click on any of the tasks (to update them) and the bootstrap modal shows up + the following code is working, so the time is formatted and datetimepicker is available.

如果我使用AJAX创建新任务(将由create.js.erb追加),然后单击该特定任务,则会显示模式,但不会触发以下代码. (如果我单击其余任务,则自页面加载以来,这些任务就按原样工作.)

If I create a new task with AJAX (will be appended by create.js.erb) and then click on that certain task the modal shows up but the following code doesn't get fired. (If I click on the rest of the tasks, those are working as they are there since page load.)

如何使它正常工作?我想让代码也可以在页面加载和页面更改时使用.由于这是用户触发的事件,因此希望不会触发两次. sby可以为我推荐一个清晰的很好的解释/文章如何组织我的js文件吗?正如我上面提到的,我读了很多,但是我变得更加困惑.

How can I make this working? I want to have the code to be available on page load and page change as well. Since this is a user triggered event hopefully doesn't get fired twice. Can sby recommend me a clear good explanation/article how I should organize my js files? As I mentioned above I read a bunch of them but I just got even more confused.

js文件

var ready = function() {
   $('.updatetask').on('shown.bs.modal', function (e) {
     alert('haha');
     var modalId = $(this).attr('id');
     var deadlineField = $("#" + modalId).find($('.edit-task-deadline'));
     var deadlineValue = $(deadlineField).attr('value');
     var momentDeadline = moment(deadlineValue).format('MM/DD/YYYY hh:mm A');
     $(deadlineField).val(momentDeadline);
   });

   $(function () {
     $('.new-task-deadline').datetimepicker({
      sideBySide: true,
      format: 'MM/DD/YYYY hh:mm A',
      stepping: 15,
      widgetPositioning: { vertical: 'bottom' }
    });
  });
};

$(document).ready(ready);
$(document).on("page:load", ready);

_task.html.erb部分

_task.html.erb partial

  ........
    <%= link_to edit_user_task_path(id: task.id), remote: true, type: "button" do %>
          <i class="fa fa-pencil" data-toggle="modal" data-target="#updatetask_<%= task.id %>"></i>
        <% end %>
        <!--Modal for updating task -->
        <%= form_for([@user, task], method: :patch, remote: true) do |f| %>
          <div class="modal fade updatetask" id="updatetask_<%= task.id %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
              <div class="modal-content" style="text-align:left">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                  <h4 class="modal-title" id="myModalLabel">Edit Task</h4>
                </div>
                <div class="modal-body">
                  <div class="alert alert-danger" style="display:none">
                    <ul class="errors" style="display:none">
                      <%= render 'layouts/error_messages', object: f.object %>
                    </ul>
                  </div>
                  <div class="field form-group">
                    <% if current_user.id == task.assigner.id %>
                      <p><strong>Executor: <%= task.executor.profile.first_name %> <%= task.executor.profile.last_name %>, <%= task.executor.profile.company %></strong></p>
                    <% else %>
                      <p><strong>Assigner: <%= task.assigner.profile.first_name %> <%= task.assigner.profile.last_name %>, <%= task.assigner.profile.company %></strong></p>
                    <% end %>
                  </div>
                  <div class="field form-group">
                    <%= f.label :content %>
                    <%= f.text_area :content, class: "form-control edit-content" %>
                  </div>
                  <div class="field form-group">
                    <%= f.label :deadline %>
                    <%= f.text_field :deadline, class: "form-control edit-task-deadline" %>
                  </div>    
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal" id="updatetaskclose">Close</button>
                    <%= f.submit "Update Task", class: 'btn btn-primary edit-task-submit', "data-sid" => current_user.id, "data-rip" => :executor_id %>
                </div>
              </div>
            </div>
          </div>
        <% end %>
        <!--Modal end for update task --> 
      </td>

create.js.erb

create.js.erb

$("ul.errors").html("");
<% if @task.errors.any? %>
  //modal error messages get inserted via AJAX
  $('.alert-danger').show();
  $('ul.errors').show();
  <% @task.errors.full_messages.each do |message| %>
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>"));
  <% end %>
<% else %>
  //hiding modal on creation and setting values to zero for optional new modal
  $('ul.errors').hide();
  $('.alert-danger').hide();
  $("#newtask").modal('hide');
  $(".task_name_company").val('');
  $(".contentarea").val('');
  $(".new-task-deadline").val('');

  //different div class for different partials + table rows get inserted into view via AJAX
  $(".newtaskinsert").prepend('<%= j render @task %>');
  $(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
  $("#task_<%= @task.id %>").hide().fadeIn(1000);
<% end %>

其他代码:

这是我用于新任务的示例代码(这很容易,因为只有一个模态而没有ID.)

Here is the sample code I'm using for new task (it's easier since there is just one modal with no ID.)

我希望它既可以用于文档更新也可以用于AJAX添加的代码进行更新.必须使用模式ID而不是表单ID来调用Submit.

I'd like to have it for updates as well both on document ready and AJAX added code. Submit must be called on the modal id not the form id.

新任务的工作代码:

$('.new-task-submit').on('click', function (e){
  e.preventDefault();
  var localMoment = moment($('.new-task-deadline').val());
  $('.new-task-deadline').val(localMoment.toISOString());
  $('#newtask').submit();
});

我尝试执行更新任务:

edit_task_submit($(document.body));
.....
......
function edit_task_submit($container) {
  $container.find('.edit-task-submit').on('click', function (e){
    e.preventDefault();
    var deadlineField = $(this).find($('.edit-task-deadline'));
    var localMoment = moment((deadlineField).val());
    deadlineField.val(localMoment.toISOString());
    alert(deadlineField.val());
    $(this).submit();
  });
}

update.js.erb

update.js.erb

<% else %>
  $('ul.errors').hide();
  $('.alert-danger').hide();
  $('#updatetask_<%= @task.id %>').modal('hide');

  $task = $('<%= j render @task %>');
  edit_task_submit($task);

  $('#task_<%= @task.id %>').fadeOut(400, function(){
      $(this).remove();
      //$(".newtaskinsert").prepend('<%= j render @task %>');
      $(".newtaskinsert").prepend('$task');
      $(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
  });
<% end %>

推荐答案

$(document).ready在加载页面时执行一次. create.js.erb创建不应用此功能的新元素.

$(document).ready executed once, when the page is loaded. create.js.erb creates new elements, for which this function is not applied.

重新组织代码,如下所示:

Reorganize your code as follows:

js文件:

function updatetask($container)
{
  $container.find('.updatetask').on('shown.bs.modal', function (e)
  {
    var deadlineField = $(this).find('.edit-task-deadline');
    var deadlineValue = deadlineField.val();
    var momentDeadline = moment(deadlineValue).format('MM/DD/YYYY hh:mm A');
    deadlineField.val(momentDeadline);
  });
}

function new_task_deadline($container)
{
  $container.find('.new-task-deadline').datetimepicker({
    sideBySide: true,
    format: 'MM/DD/YYYY hh:mm A',
    stepping: 15,
    widgetPositioning: { vertical: 'bottom' }
  });
}

$(function () // shortcut for $(document).ready
{
  updatetask($(document.body));
  new_task_deadline($(document.body));
});

create.js.erb:

create.js.erb:

$("ul.errors").html("");
<% if @task.errors.any? %>
  //modal error messages get inserted via AJAX
  $('.alert-danger').show();
  $('ul.errors').show();
  <% @task.errors.full_messages.each do |message| %>
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>"));
  <% end %>
<% else %>
  //hiding modal on creation and setting values to zero for optional new modal
  $('ul.errors').hide();
  $('.alert-danger').hide();
  $("#newtask").modal('hide');
  $(".task_name_company").val('');
  $(".contentarea").val('');
  $(".new-task-deadline").val('');

  // time formatting and datetimepicker for new elements
  $task = $('<%= j render @task %>');
  updatetask($task);
  new_task_deadline($task);

  //different div class for different partials + table rows get inserted into view via AJAX
  $(".newtaskinsert").prepend($task);
  $(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
  $("#task_<%= @task.id %>").hide().fadeIn(1000);
<% end %>

有关更新:

edit_task_submit($(document.body));

function edit_task_submit($container)
{
  $container.find('.edit-task-submit').on('click', function (e)
  {
    e.preventDefault();
    var $this = $(this);
    var deadlineField = $this.closest('form').find('.edit-task-deadline');
    var localMoment = moment(deadlineField.val());
    deadlineField.val(localMoment.toISOString());
    $this.click();
  });
}

update.js.erb:

update.js.erb:

<% else %>
  $('ul.errors').hide();
  $('.alert-danger').hide();
  $('#updatetask_<%= @task.id %>').modal('hide');

  $task = $('<%= j render @task %>');
  edit_task_submit($task);

  $('#task_<%= @task.id %>').fadeOut(400, function()
  {
    $(this).remove();
    $(".newtaskinsert").prepend($task);
    $(".newtaskinsert2").prepend('<%= j render partial: "tasks/task_between", locals: { task: @task } %>');
  });
<% end %>

这篇关于没有涡轮链接的AJAX之后在rails中触发js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆