4
buildIMG = (src, resize) ->
  html  = '<div class="left"><div class="foods_image">'
  html += '<a onclick="popitup("http://somewhere.com/test" href="javascript:void(0)">'
  html += '   <img src="'+src+'" '+resize+' />'  
  html += '</a>'
  html += '</div></div>'
  html

popitup = (url) ->
  newwindow=window.open(url,'name','height=640,width=640')
  newwindow.focus() if window.focus
    false

我目前有一个小书签,可将 javascript 代码(上述代码)插入网站。我写了上面的咖啡脚本,它生成了这个:

(function() {
  var buildIMG, popitup;

  buildIMG = function(src, resize) {
    var html, nbsp;
    html = '<div class="left"><div class="foods_image">';
    html += '<a onclick="popitup(\'http://somewhere.com/test\');" href="javascript:void(0)">';
    html += '   <img src="' + src + '" ' + resize + ' />';
    html += '</a>';
    html += '</div></div>';
    return html;
  };
  popitup = function(url) {
    var newwindow;
    newwindow = window.open(url, 'name', 'height=640,width=640');
    return newwindow.focus()(window.focus ? false : void 0);
  };
}).call(this);

我剪掉了使用 buildIMG 的函数。该函数在站点上创建一个覆盖并显示该覆盖中的所有图像。为每个图像调用 buildIMG 以创建 html。

问题是这onclick="popitup("http://somewhere.com/test"部分不起作用。它是未定义的。

我所做的一个解决方案是删除由 CoffeeScript 生成的这个:

(function() {

}).call(this);

我一删除它就修复了。如何在我生成的 javascript 中没有将 CoffeeScript 放入这些行中?

4

2 回答 2

19

CoffeeScript 允许在没有这个安全包装器的情况下通过--bare选项编译 JavaScript。

于 2012-04-04T10:29:18.037 回答
5

尽管为了清楚起见在本文档中被隐藏,但所有 CoffeeScript 输出都包装在一个匿名函数中: (function(){ ... })(); 这个安全包装器与 var 关键字的自动生成相结合,使得意外污染全局命名空间变得极其困难。

它来自 CoffeScript 网站。如果要创建全局方法或变量,则需要

root = this
localProperty = "111"
root.property = localProperty

然后您将获得全局范围内的属性。

于 2012-04-04T10:25:57.020 回答