简体   繁体   English

从调用咖啡脚本定义的函数<script> in html?

[英]Calling coffeescript defined function from <script> in html?

I have a rails app and I am rewriting all my JS in CoffeeScript just to check it out. 我有一个Rails应用程序,我正在用CoffeeScript重写我的所有JS,只是为了将其签出。

I understand CoffeeScript compiles to JS but I am having trouble with something. 我了解CoffeeScript可以编译为JS,但遇到了一些问题。

I am using Google Maps API and I have a script tag in one of my html.erb files as follows: 我正在使用Google Maps API,并且在我的html.erb文件之一中有一个脚本标记,如下所示:

<script>
initialize()
</script>

Now my initialize used to work because it was just written in javascript, but now that I have a coffeescript function instead the browser console says: 现在我的初始化方法可以正常工作了,因为它只是用JavaScript编写的,但是现在有了咖啡脚本功能,浏览器控制台会说:

"Uncaught ReferenceError: initialize is not defined"

I put this at the bottom of the coffeescript file after the function definition, but still no dice. 我将其放在函数定义之后的coffeescript文件的底部,但仍然没有骰子。

window["initialize"] = initialize

This really does not have anything to do with CoffeeScript vs JS. 这确实与CoffeeScript vs JS无关。 But is rather due to the fact that your inline script is run before the external file which declares window.initialize is run. 而是由于您的内联脚本在声明window.initialize的外部文件运行之前运行。

Its widely accepted that inline script tags are a bad practice. 内联脚本标记是一种不好的做法,这一点已被广泛接受。 So start out by getting rid of it. 因此,从摆脱它开始。

This is an example of how you can use the google loader & jQuery.Deferred instead of a global callback function: 这是如何使用google loaderjQuery.Deferred而不是全局回调函数的示例:

jQuery(function(){
  var apiLoaded = jQuery.Deferred();
  var mapInit = jQuery.Deferred();
  var $map_canvas = $('#map_canvas');

  if ( $map_canvas.length ) {
    google.load("maps", "3", { other_params:'sensor=false', callback: function(){
      apiLoaded.resolve(google);
    }});

    apiLoaded.done(function(g){
      var map = new g.maps.Map($map_canvas[0],{
          center: new google.maps.LatLng(63.399313, 13.082236),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      mapInit.resolve(map);
    });

    mapInit.done(function(map){
      // do something with the map!
    });
  }
});

In case you are not using jQuery or the loader you need to use polling to check if the google maps API is loaded: 如果您未使用jQuery或加载器,则需要使用轮询来检查是否加载了google maps API:

function init(gmaps){
    // do something with the maps api...
}

function isLoaded(){
  if (!window.google){
    window.setTimeout(function(){ isLoaded() }, 10);
  } else {
     init(window.google.maps);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM