Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript equivalent to On Document Ready

I am trying to use Coffeescript, but I am having a problem on my web application. Its methods are not called until I reload the page.

I think that what is missing is the $(document).ready(function () { part, but I couldn't find how to do it in the web.

file_name.js (works great)

$(document).ready(function () {
  $(document).on('click', '.add_fields', function(event) {
    event.preventDefault();
    /* Act on the event */
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
  });
});

file_name.coffee (doesn't work)

jQuery ->
  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()

How can I fix this?

like image 519
Augusto Carmo Avatar asked May 20 '18 01:05

Augusto Carmo


People also ask

What is JavaScript equivalent of document ready?

Answer: Use the DOMContentLoaded Event You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.

Why document ready is deprecated?

Why document ready is deprecated? As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the . ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.

What is difference between $( function () and document Ready?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.


1 Answers

$(document).ready ->

See example at https://github.com/jashkenas/coffeescript/blob/master/documentation/site/docs.coffee#L16

like image 57
Geoffrey Booth Avatar answered Oct 06 '22 01:10

Geoffrey Booth