我可以从coffeescript文件调用一个Javascript函数吗? [英] Can I call a Javascript function from a coffeescript file?
问题描述
我试图从Coffeescript文件中为我的 $(document).ready()
调用一个javascript函数,它从不被调用。
I'm trying to call a javascript function from a Coffeescript file, for my $(document).ready()
and it's never getting called.
我想要调用的函数来自我在html head元素中包含的外部源,就在coffeescript文件的include之前,如下所示:
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 %>
并且在我的coffeescript文件(称为someControllerName.coffee)中,我这样做:
and in my coffeescript file (called someControllerName.coffee) I do this:
ready = ->
... call my method
$ -> ready
这是正确的方法吗?我可以在Chrome中看到我的脚本被编译为javascript,我可以在检查器的网络选项卡中看到它。
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.
我使用Rails 4,是我的application.js
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 .
编辑:
方法调用 alert(...);
它工作,如果我调用我的javascript方法使用javascript在 $(document).ready ()
它工作正常。
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:
:
var ready = function () {
$('pre code').each(function (i, e) {
hljs.highlightBlock(e)
});
};
$(document).ready(ready);
我解决了这个问题:
highlight = ->
$("pre code").each (i, e) ->
hljs.highlightBlock(e)
$(document).on 'ready page:load', ->
highlight()
推荐答案
做你认为它做的事:
$ -> ready
在JavaScript中:
In JavaScript that is:
$(function() {
return ready;
});
您的问题是只要准备
对函数的引用,它不是一个函数调用,就像它会在Ruby中。你必须说 ready()
才能调用函数,调用括号的函数只有在调用带有参数的函数时才是可选的: fx
和 f(x)
是相同的,但 f
和 f()
不同。
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.
我想你想说:
$ -> ready()
或甚至:
$ ready # same as $(ready)
这篇关于我可以从coffeescript文件调用一个Javascript函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!