Can I call a Javascript function from a coffeescri

2019-03-05 12:20发布

问题:

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()

回答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)