简体   繁体   中英

How to run a function after an external JS script finishes running

I am trying to understand how to ensure my code runs after an external JS file has finished running.

If you need a specific implementation, you can look at this SO question, which I am trying to help answer: How to get the last table row no matter the sort?

TDLR : The script found in bootstrap-sortable.js runs a table sort. After this table sort is complete; I want to make it so that I can run a snippet, which will add a simple CSS class to the last element in the freshly sorted table. The adding of the class can easily be achieved by this JQuery snippet:

var lastRow = $(this).closest("table").find("tbody tr:last");

if(!lastRow.hasClass("dropup")){
    // Removing dropup class from the row which owned it
    $(this).closest("table").find("tbody tr.dropup").removeClass("dropup");
    // Adding dropup class to the current last row
    lastRow.addClass("dropup");
}

I would like to know:

  1. Is it possible to run my script after the external script is done running?
  2. If not, can you explain why?
  3. I have already considering modifying bootstrap-sortable.js to add my script to it, is this the best recommendable approach?

Bonus round! (only if you feel you need the challenge).

Is there a better, do-it-yourself, solution for sorting the table other than using bootstrap-sortable.js for the linked question?

Thanks everyone!

I want to thank Dave Newton for leading me to the answer to this question which is quite simple.

JSFiddle

$(document).ready(function() {
  $("#MyTable").on('sorted', function(){
    var lastRow = $("#MyTable").find("tbody tr:last");
      // Removing dropup class from the row which owned it
      $("#MyTable").find("tbody tr.dropup").removeClass("dropup");
      // Adding dropup class to the current last row
      lastRow.addClass("dropup");
  });
});

This is awesome, simple and lightweight, it also adheres to the linked question. Thanks Dave!

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