移除CoffeeScript匿名函数调用

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代码(如上所示)插入到网站中。我编写了上述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);

我剪掉了使用buildIMG的函数。该函数在网站上创建一个覆盖层,并在该覆盖层中显示所有图像。对于每个图像,都会调用buildIMG来创建html。
问题在于onclick="popitup("http://somewhere.com/test" 部分不起作用。它未定义。
我做的一个解决方案是移除由CoffeeScript生成的代码:
(function() {

}).call(this);

只要我删除了它,问题就立即解决了。那么我如何才能让CoffeeScript不在我生成的JavaScript代码中添加那些行?


1
如果你不理解它的作用和原因,首先要了解它。它很巧妙、惯用,并且有充分的理由。 - user395760
那你没有理解它。整个重点在于不要将任何东西放入全局命名空间中。 - user395760
是的,非常抱歉。我之前认为调用中的“this”是窗口对象? - Teej
不一定。只有当整个代码放置在全局作用域中时才是如此。否则(例如在方法内调用),它会从周围作用域继承this - user395760
可能是 CoffeeScript 模块的模式的重复问题。 - Trevor Burnham
显示剩余3条评论
2个回答

19

CoffeeScript允许通过--bare选项编译JavaScript代码时不使用安全包装。


2
Jitter也有这个选项-b或--bare。 - Roger Garzon Nieto

5

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

这是来自CoffeScript网站的内容。 如果你想创建一个全局方法或变量,你需要:

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

然后,您将在全局范围内获得一个属性。

很棒的回答,我本来会接受这个答案的,但我的问题已经被@zbynour回答了。 - Teej
+1 这在 Rails 中非常有用,例如当您不想在命令行中编译并且不想为每个 CoffeeScript 文件禁用它时。 - comandante N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接