如何在coffeescript的insert函数中绑定@variables?

时间:2013-11-05 16:46:20

标签: javascript coffeescript

代码:

    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的问题对于此内容有误:_thisvar _this = this函数的情况下为=>

我在纯Javascript中使用that变量解决了这个问题:

 ...

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

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

1 个答案:

答案 0 :(得分:1)

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

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();
      }
    };
  });
}