lodash/underscore - 将绑定与方法调用结合使用,并且方法保持未绑定状态
lodash/underscore - using bind with method call and method remains unbound
相关代码如下:
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" 变成了 window 对象。我如何正确地将它绑定到方法?
您应该将上下文作为第二个参数传递给 bind
,而不是传递给 then
方法。
值得一提的是 underscore
不是必需的,因为您可以使用 native bind
方法:
this.createConnectorCollection.bind(this)
您的右括号似乎放错地方了:
$.when(connectorPromise, iconPromise).then(_.bind(this.createConnectorCollection, this));
相关代码如下:
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" 变成了 window 对象。我如何正确地将它绑定到方法?
您应该将上下文作为第二个参数传递给 bind
,而不是传递给 then
方法。
值得一提的是 underscore
不是必需的,因为您可以使用 native bind
方法:
this.createConnectorCollection.bind(this)
您的右括号似乎放错地方了:
$.when(connectorPromise, iconPromise).then(_.bind(this.createConnectorCollection, this));