DRY up your Javascript

Episode #41 by Teacher's Avatar David Kimura

Summary

Learn how avoid duplicate code to reuse existing javascript.
rails view performance 4:30

Resources

For more information about server side javascript, checkout these previous episodes.

Episode 20 - Not RJS and Turbolinks -  https://www.driftingruby.com/episodes/not-rjs-and-turbolinks

Episode 21 - Not RJS and Turbolinks Part 2 - https://www.driftingruby.com/episodes/not-rjs-and-turbolinks-part-2

Summary

# application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require jquery-ui/datepicker
//= require_tree .

$(document).on('turbolinks:load', date_picker_init);

# date_picker_init.js
var date_picker_init;
date_picker_init = function() {
  $('.datepicker').each(function(){
    $(this).datepicker();
  })
};
// $(document).ready(date_picker_init);

# edit.js.erb
$('#remote_container').html('<%= j render "edit" %>');
$('#edit_contact').modal('show');
$.getScript('<%= asset_path "date_picker_init" %>');
$(document).ready(date_picker_init);

In the javascript view response, we very well could have simply called on date_picker_init(); The $.getScript example is meant for making sure that the function is set prior to calling it in the event it has not already been loaded in your asset pipeline. This can be the case if you do not require your tree (require_tree .) in your application.js file. If you do wrap your javascript in a function like we have in this example and you include the function to be loaded in your application.js file, you can save a trip back to the server and simply call date_picker_init(); in the edit.js.erb. Using $.getScript is helpful when you have specific javascript assets that are not normally loaded from the asset pipeline.

# config/initializers/assets.rb
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( date_picker_init.js )