删除CoffeeScript匿名函数调用

Tee*_*eej 4 javascript coffeescript

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
Run Code Online (Sandbox Code Playgroud)

我目前有一个书签,可以将javascript代码(上面的代码)插入到网站中.我写了上面的coffeescript,它产生了这个:

(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);
Run Code Online (Sandbox Code Playgroud)

我剪断了使用buildIMG的函数.该功能在网站上创建叠加层并显示该叠加层中的所有图像.为每个图像调用buildIMG来创建html.

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

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

(function() {

}).call(this);
Run Code Online (Sandbox Code Playgroud)

我删除它后立即修复.我如何在生成的javascript中没有将CoffeeScript放入这些行?

zby*_*our 19

CoffeeScript允许在没有此安全包装的情况下编译JavaScript --bare.

  • 抖动也有这个选项-b或--bare (2认同)

Flo*_*ops 5

虽然为了清楚起见在本文档中进行了抑制,但所有CoffeeScript输出都包含在一个匿名函数中:(function(){...})(); 这个安全包装器与var关键字的自动生成相结合,使得非常难以意外地污染全局命名空间.

它来自CoffeScript网站.如果要创建所需的全局方法或变量

root = this
localProperty = "111"
root.property = localProperty
Run Code Online (Sandbox Code Playgroud)

然后你将获得全球范围内的房产.