代码之家  ›  专栏  ›  技术社区  ›  user4479529

lodash/underline-使用方法调用绑定,方法保持未绑定状态

  •  0
  • user4479529  · 技术社区  · 9 年前

    以下是相关代码:

        render: function(args, callback) {
    
            connectorPromise = ConnectorDelegate.currentConnectors();
            iconPromise = connectorUtils.getIconList();
            // when promises resolve call method and bind it to "this"
    
            $.when(connectorPromise, iconPromise).then(_.bind(this.createConnectorCollection), this);
        },
    
        createConnectorCollection: function(connectors, iconList) {
           // This is the window object in here
        }...
    

    在呈现方法中,“this”被正确绑定。然而,当我调用createConnectorCollection方法时,“this”将成为窗口对象。如何将其正确绑定到方法?

    2 回复  |  直到 9 年前
        1
  •  0
  •   Ad.Infinitum    9 年前

    您的右括号似乎放错了位置:

    $.when(connectorPromise, iconPromise).then(_.bind(this.createConnectorCollection, this));
    
        2
  •  0
  •   Роман Парадеев    9 年前

    您应该将上下文作为第二个参数传递给 bind ,不是到 then 方法

    值得一提的是 underscore 不需要,因为您可以使用 native 绑定 方法:

    this.createConnectorCollection.bind(this)
    
    推荐文章