#41 DRY up your Javascript
Summary
Learn how avoid duplicate code to reuse existing javascript.rails view performance 4:30
Resources
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
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.jsvar 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 )
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.
bootstrap event $('#edit_contact').modal('show') inside of popup its appear below the page is there any solution to solve this problem.