Callback inside the class constructor


#1

Hi all,

Trying to define the class like that:

export class Map {

constructor(parentTemplate, mapName, images, defaultLocation) {
    this.mapInstance = {};
    this.state = new ReactiveDict();

    GoogleMaps.ready(mapName, this.onMapReady);    <<call back

}

onMapReady(map) {
this.mapInstance = map;
this.state.set('mapField', this.getField());  <<state is undefined (???)
}
getField() {
   return {'fsfsdfsfdsdf'};
}

but the ‘state’ var is undefined on callback call.

Any ideas ?


#2
  1. You have a simple class or do you want a class that extends React.Component ?
  2. Read this by Dan Abramov:
    https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.gbr22q8xu
  3. Don’t do it in the constructor, do it in componentWillMount : https://facebook.github.io/react/docs/react-component.html#componentwillmount , you will have access to “this.props” that you pass to your Map Component

Good luck!


#3

I do not use React …


#4

Oh I’ve been so blind. Sorry!

Ok so the reason is that you pass in a function but you need to bind it’s context do it like this:

GoogleMaps.ready(mapName, this.onMapReady.bind(this));

#5

Much better, thanks …


#6

Have to ask again,

My constructor consumes reactive var later inside the tracker call

    constructor( .....
...
...
    Tracker.autorun(() => {
        console.log('loadMapMarkers triggered');
        Meteor.subscribe('xxx', this.state.get('yyyy'));
        this.loadMapMarkers();   << THIS CALL FAIL
    });

where loadMapMarkers is the same object method and then calls other method (of the same object again):

loadMapMarkers() {
        this.defMapMarker(); << BECAUSE THAT ONE is undefined
     }
defMapMarker() {
        console.log('never run'); 
     }

So the problem is the call of the second nested method.


#7

Bind your methods:

constructor () {
  this.defMapMarker = this.defMapMarker.bind(this);
}

or

defMapMarker = () => {
  ...
}

#8

and then

depMapMarker (){
 something;
}

???

It’s working without given constructor line.

Edit:

Solved after found that one of the inner forEach loops was not converted into new syntax, instead of

xxx.forEach((yyyy) => {})

it was:

xxx.forEach( function (yyyy) {})

I had to be blind …