Callback on wrong scope

2019-07-20 13:52发布

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条回答
Summer. ? 凉城
2楼-- · 2019-07-20 14:20

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

查看更多
登录 后发表回答