#41 DRY up your Javascript


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


Source - https://github.com/driftingruby/041-dry-up-your-javascript

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


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.jsvar date_picker_init;
date_picker_init = function() {
// $(document).ready(date_picker_init);
edit.js.erb$('#remote_container').html('<%= j render "edit" %>');
$.getScript('<%= asset_path "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 )
stephane.cedroni said about 3 years ago on DRY up your Javascript :

Hi, is there a reason you use both $document('ready') and 'turbolinks:load' listeners? As far as I know 'turbolinks:load' should be called on initial page load as well, making $document('ready') redundant.

kobaltz PRO said about 3 years ago on DRY up your Javascript :

It's a strange situation where you have two acting parts. The initial form when creating a new contact would trigger the date picker from turbolinks:load. However, when you go to edit the contact, the turbolinks:load would not trigger since it is a server generated javascript being sent back. In hindsight, the document.ready should be removed from the date_picker_init.js file and placed under the edit.js.erb since it is more applicable there. 

Rehan Khan said almost 3 years ago on DRY up your Javascript :

bootstrap event $('#edit_contact').modal('show') inside of popup its appear below the page is there any solution to solve this problem.

Login to Comment