简体   繁体   中英

Implementing a loading spinner

I am trying to implement a loading spinner in rails 5. The spinner is suposed to appear and spin when an object is deleted from a table view (also deleted from the database). The delete action is being handled in a file called destroy.js.erb. The problem is that I specified the sequence of events to be: 1. Show the spinner 2. delete from the database 3. send a notification email 4. hide the spinner

But for some reason when I press the delete button, steps 2 and 3 happen first and then 1 happens. Even though the order is clear!

If I remove the delete and send functions (which are handled in rails), the javascript order executes correctly (for example just to show and then hide the spinner immediately). But as soon as there is a rails operation between step 1 and 4, the order is messed up.

I have already tried several things that did not work:

  1. I tried running the rails operations inside the destroy controller then render destroy.js.erb to show and hide the spinner (obviously did not work because it will always run ruby first)

  2. I tried to do everything in the js.erb file, by specifying the order mentioned above and using embedded ruby for the operations... also did not work because the ruby code is always executed first.

Any help would be appretiated.

Here is the code for my destroy.js.erb:

$("#spinner").show();

$("#internal_request_<%= @request.id %>").remove();

"<%@request.destroy%>";

"<%CancelRequestMailer.cancel_request_email(@current_requester, @recipients, @request).deliver%>";

$("#spinner").hide();

Here is the code for application.js

//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require jquery

$( document ).ready(function() {

  // hide spinner
  $("#spinner").hide();
});

Here is the html.erb for the button

<%= link_to request, :method => :delete, data: {:confirm => "Are you sure?"}, remote: true do %>
  <button type="button" class="btn btn-outline-danger">
    <i class="fas fa-ban fa-fw"></i>
  </button>
<% end %>

Again... All this is working... It is just that the order is wrong... The spinner only appears when everything is already done (deletion, email sent..)

It should appear before and stay while the operations are being performed and then go away.

Rather than reinvent the wheel, take a look at some common libraries and frameworks that are available. These are often better maintained and customizable than custom code.

I prefer Twitter Bootstrap's spinners . There are lots of unique options and it's very customizable.

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