Coffeescript理解和封闭问题

时间:2011-09-30 16:07:37

标签: coffeescript

将一些JavaScript转换为CoffeeScript时遇到了问题。基本问题是我从使用$ .each到CoffeeScript理解,现在我遇到了一个问题,即闭包中捕获了理解的最后一个值。让我们从最初的JavaScript开始:

function bindKeyboardControls(websocket) {
    var moveKeyMap = {
        Down: ['down', 's'],
        Up: ['up', 'w'],
        Left: ['left', 'a'],
        Right: ['right', 'd']
    };

    $.each(moveKeyMap, function (direction, keys) {
        $.each(keys, function (_, key) {
            $(document).bind('keydown', key, function () { move(websocket, direction); });
        });
    });
};

这是我第一次尝试使用CoffeeScript:

    bindKeyboardControls = (websocket) ->
    moveKeyMap =
        Down: ['down', 's']
        Up: ['up', 'w']
        Left: ['left', 'a']
        Right: ['right', 'd']        
    for direction, keys of moveKeyMap
        for key in keys
            $(document).bind('keydown', key, -> move(websocket, direction))
    null

为什么这不起作用?那么这里是生成的JavaScript:

bindKeyboardControls = function(websocket) {
  var direction, key, keys, moveKeyMap, _i, _len;
  moveKeyMap = {
    Down: ['down', 's'],
    Up: ['up', 'w'],
    Left: ['left', 'a'],
    Right: ['right', 'd']
  };
  for (direction in moveKeyMap) {
    keys = moveKeyMap[direction];
    for (_i = 0, _len = keys.length; _i < _len; _i++) {
      key = keys[_i];
      $(document).bind('keydown', key, function() {
        return move(websocket, direction);
      });
    }
  }
  return null;
};

您是否看到如何在函数顶部声明'direction'变量?传递给document.bind的函数是在该变量上创建一个闭包,因此在函数运行时,方向将始终等于最后一个值('Right')。

这是一个有点难看的固定版本:

    bindKeyboardControls = (websocket) ->
    moveKeyMap =
        Down: ['down', 's']
        Up: ['up', 'w']
        Left: ['left', 'a']
        Right: ['right', 'd']        
    for direction, keys of moveKeyMap
        for key in keys                             
            ((d) -> $(document).bind('keydown', key, -> move(websocket, d)))(direction)
    null        

我还可以回到使用$ .each。所以我确实有一些解决方案,但有更好的解决方案吗?

1 个答案:

答案 0 :(得分:5)

是:

for direction, keys of moveKeyMap
  for key in keys
    do (direction, key) -> $(document).bind('keydown', key, -> move(websocket, d))

创建并运行一个匿名函数,捕获directionkey的值,以便bind回调可以使用它们。有关详细信息,请参阅我的PragProg文章A CoffeeScript Intervention