0

代码:

    class FileTree
      constructor: (@root_elem, @options, @handler) ->

      _bind_tree: (t) ->
        that = this
        $(t).find('li a').bind('click', ->
          func1 = (elem) =>
            if( @options.some_option ) 
      ...

@options转换_this.options为该内容的问题是错误的:_this是函数var _this = this的情况=>

that我通过使用纯 Javascript 中的变量来解决这个问题:

 ...

func1 = (elem) =>
    if( that.options.some_option ) 
 ...

有没有不使用临时变量的漂亮解决方案?

4

1 回答 1

1

假设您想@options成为@optionsFileTree 构造函数的,您还需要在点击处理程序上使用胖箭头:

class FileTree
  constructor: (@root_elem, @options, @handler) ->

  _bind_tree: (t) ->
    $(t).find('li a').bind('click', =>
      func1 = (elem) =>
        if @options.some_option
          doStuff()

编译为:

FileTree.prototype._bind_tree = function(t) {
  var _this = this; // will refer to the instance of FileTree
  return $(t).find('li a').bind('click', function() {
    var func1;
    return func1 = function(elem) {
      if (_this.options.some_option) {
        return doStuff();
      }
    };
  });
}
于 2013-11-05T17:14:51.067 回答