Callback on wrong scope

大城市里の小女人 提交于 2019-12-11 00:14:45

问题


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 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>

Component Controller:

heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
    this.heatMapLayer = heatLayer;
    // 'this' here is not my controller
}

If I change the call back to

<ui-gmap-layer onCreated="$ctrl.heatLayerCallback(layer)"></ui-gmap-layer>

Then my callback executes on the right scope (i.e. my controller) but the parameter layer is lost ;/

Notes

I am using Typescript, Angular 1.6 and Angular Components


回答1:


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:

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

...or:

var that = this; // store this or whatever context you want
...
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
    that.heatMapLayer = heatLayer;

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").



来源:https://stackoverflow.com/questions/45508846/callback-on-wrong-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!