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()
-
I reckon its probably your function within the coffeescript file? If alert works but not a method call it might be your methodSherwyn Goh– Sherwyn Goh2014年01月24日 03:33:42 +00:00Commented Jan 24, 2014 at 3:33
-
I added my real javascript function, could you tell me how you would implement it in coffeescript?Pacane– Pacane2014年01月24日 12:31:19 +00:00Commented Jan 24, 2014 at 12:31
1 Answer 1
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)
2 Comments
$(document).on 'ready page:load', ready too.Explore related questions
See similar questions with these tags.