错误范围的回调 [英] Callback on wrong scope
问题描述
我有一个问题,不记得如何解决.我正在订阅来自第三方指令的回调,但未使用正确的范围进行回调.而且我的意思是,当它击中我的控制器 this
时,我实际上还无法确定其他范围,因此它无法访问任何成员变量.我如何回到我的控制器范围?
< ui-gmap-layer type ="HeatmapLayer" onCreated ="$ ctrl.heatLayerCallback"></ui-gmap-layer>
组件控制器:
heatLayerCallback(heatLayer:google.maps.visualization.HeatmapLayer){this.heatMapLayer = heatLayer;//这里的'this'不是我的控制器}
如果我将呼叫改回
< ui-gmap-layer onCreated ="$ ctrl.heatLayerCallback(layer)"></ui-gmap-layer>
然后我的回调在正确的范围(即我的控制器)上执行,但是参数 layer
丢失了;/
注释
我正在使用Typescript,Angular 1.6和Angular组件
您可以使用 ...或: 确切的语法可能会有所不同,具体取决于引用的代码所在的位置(例如,找到所需的"this",或使用任何上下文代替"this"). I have an issue and can't remember how to get around it. I am subscribing to a callback from a third party directive but not being called back with the correct scope. And by that I mean that when it hits my controller Component Controller: If I change the call back to Then my callback executes on the right scope (i.e. my controller) but the parameter Notes I am using Typescript, Angular 1.6 and Angular Components You could use bind to bind the callback to the context you want (your controller) or simply store it in another new variable before the callback and access it by that variable within the callback. Something like: ...or: The precise syntax may vary depending on where your quoted code lives (e.g. find where "this" is what you want, or use whatever context instead of "this"). 这篇关于错误范围的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
var that = this;//存储此内容或您想要的任何上下文...heatLayerCallback(heatLayer:google.maps.visualization.HeatmapLayer){that.heatMapLayer = heatLayer;
this
is actually some other scope I cant quite figure out so it cannot access any member variables. How do I get back to my controller scope?<ui-gmap-layer type="HeatmapLayer" onCreated="$ctrl.heatLayerCallback"></ui-gmap-layer>
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
this.heatMapLayer = heatLayer;
// 'this' here is not my controller
}
<ui-gmap-layer onCreated="$ctrl.heatLayerCallback(layer)"></ui-gmap-layer>
layer
is lost ;/var heatLayerCallback = (function(heatLayer: google.maps.visualization.HeatmapLayer) {
this.heatMapLayer = heatLayer;
// 'this' here is now the same as the 'this' outside/below
}).bind(this); // bind to this or whatever context you want
var that = this; // store this or whatever context you want
...
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
that.heatMapLayer = heatLayer;