0

I'm trying to call a javascript function from a Coffeescript file, for my $(document).ready() and it's never getting called.

The function I want to call comes from an external source that I have included in my html head element, just before the include of my coffeescript file, like this:

<script src="external.js"></script>
<%= javascript_include_tag params[:controller], 'data-turbolinks-track' => true %>

and in my coffeescript file (called someControllerName.coffee) I do this:

ready = ->
  ... call my method

$ -> ready

Is this the correct way? I can see in Chrome that my script is compile to javascript, and I can see it in the Network tab of the inspector.

I'm using Rails 4, and this is my application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .

edit:

If I replace my method call by alert("..."); it works, and if I call my javascript method using javascript in $(document).ready() it works fine.

edit2:

Here's my real javascript function:

var ready = function () {
  $('pre code').each(function (i, e) {
      hljs.highlightBlock(e)
  });
};

$(document).ready(ready);

I solved the problem doing this:

highlight = ->
  $("pre code").each (i, e) ->
    hljs.highlightBlock(e)

$(document).on 'ready page:load', ->
  highlight()
2
  • I reckon its probably your function within the coffeescript file? If alert works but not a method call it might be your method Commented Jan 24, 2014 at 3:33
  • I added my real javascript function, could you tell me how you would implement it in coffeescript? Commented Jan 24, 2014 at 12:31

1 Answer 1

3

This doesn't do what you think it does:

$ -> ready

In JavaScript that is:

$(function() {
    return ready;
});

Your problem is that just ready is simply a reference to the function, it is not a function call like it would be in Ruby. You'd have to say ready() to call the function, the function calling parentheses are only optional when you're calling a function with arguments: f x and f(x) are the same but f and f() are different.

I think you want to say:

$ -> ready()

or even:

$ ready # same as $(ready)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, now my function gets called, but it doesn't compile because of errors. I have included in my original post my real javascript function, if you could help me figuring out how to implement it in coffeescript.
You got this figure out while I was away, right? You should be able to say just $(document).on 'ready page:load', ready too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.