Callback on wrong scope
Asked Answered
D

1

2

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

Decalcomania answered 4/8, 2017 at 14:2 Comment(0)
G
2

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

Genteelism answered 4/8, 2017 at 14:11 Comment(5)
Thanks Will, any idea how to work this in typescript? I think by default typescript will do var that = thisDecalcomania
As TypeScript is a superset of JavaScript, either approach should work. Again, depending on what the rest of your code looks like, the original this in my examples may not be the right context. Use (bind to or store) whatever context you need for your situation. I'll also update the bind example with a bit more explanation.Genteelism
Thanks Will but its still not working, ill update my question with what ive triedDecalcomania
Cool, it would probably help to see a lot more of your code, most importantly where the function is declared within the controller.Genteelism
I re-read my code and realised I'd made a mistake, your answer [the top one] works, thanks!Decalcomania

© 2022 - 2024 — McMap. All rights reserved.