1

I cannot seem to be able to pass a string from html

<div class="download-by-date" data-hello="dd/mm/yy">

to coffeescript:

$('.datepicker').datepicker({ dateFormat: $(this).data('hello') })

Here is the code from the slim file

= render layout: 'shared/section', locals: { title: 'Export on Demand', description: "Use this section to export all orders within a particular date period or starting from a reference" } do
  .download-by-date data-hello='dd/mm/yy'
    .row
      .column.medium-6
        label

How can I read the data-hello attribute correctly in my coffeescript file? I'm trying to get this in coffeescript:

$('.datepicker').datepicker({ dateFormat: "dd/mm/yy" })

Nima
  • 3,309
  • 6
  • 27
  • 44
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35

1 Answers1

2

You can use either of these:

/*
#coffee script:

$('.download-by-date').on 'click', ->
  $('.datepicker').datepicker { dateFormat: $(this).data 'hello' }
*/

//compiled javascript
$('.download-by-date').on('click', function() {
  return $('.datepicker').datepicker({
    dateFormat: $(this).data('hello')
  });
});

Or

/*
#coffee script:

$('.download-by-date').on 'click', => 
  format = $('.download-by-date').data "hello"; 
  $('.datepicker').datepicker { dateFormat: format }
*/

//compiled javascript
$('.download-by-date').on('click', () => {
  var format;
  format = $('.download-by-date').data("hello");
  return $('.datepicker').datepicker({
    dateFormat: format
  });
});

Notice the difference between use of ->(thin arrow) and =>(fat arrow). The fat arrow binds the callback function to value of this at the definition spot. You want to use thin arrow here.

For more info refer:
Bound (Fat Arrow) Functions
CoffeeScript, When to use fat arrow (=>) over arrow (->) and vice versa

the Hutt
  • 16,980
  • 2
  • 14
  • 44
  • The crucial piece of information I was looking for was `format = $('.download-by-date').data "hello"`. Many thanks @onkar – Sagar Pandya Jan 10 '22 at 11:46