This is probably more a general JS encapsulation issue than Rails asset pipeline.
In the asset pipeline I have some general JS files that are used everywhere:
app/assets/javascripts/pickers.js.cofeee
jQuery ->
$('.datetimepicker').datetimepicker
dateFormat: 'yy-mm-dd',
timeFormat: 'h:mmtt',
ampm: true,
hourGrid: 4,
minuteGrid: 10
$('.datepicker').datepicker
dateFormat: 'yy-mm-dd'
I also target body classes to run specific JS on controller/action specific pages:
app/assets/javascripts/employees.js.cofeee
jQuery ->
if $('.employees.edit').length
# initialize datepickers when adding new nested fields
$('form').live 'nested:fieldAdded', (e) ->
$(e.field).find('.datepicker').removeClass('hasDatepicker').datepicker
dateFormat: 'yy-mm-dd'
Now this isn’t the most cumbersome example of repetition but hypothetically if I wanted to move this datepicker code into a function and then call it in the employees.js.coffee file, how could I do that?
You extract the function into the global scope (outside of
jQuery). Then it’s available anywhere in your Javascript code as it becomes a member of thewindowobject.You should read about scopes in Javascript.