Search code examples
javascriptoopleafletleaflet-geoman

Setting event listener of a class property


I'm using Leaflet and Leaflet-geoman in conjunction with wfs-t to create an editable map object. I have a class EditMap that has a leaflet map as a property. I'm trying to listen for the 'pm:create' event on this map for every class. Here is my code:

class EditMap {
    constructor(map){
        this.map = map;//Leaflet map
    }
    this.map.on('pm:create', e => {
        console.log('Feature created');
    });
}

I get the error Uncaught SyntaxError: Unexpected token '.' on this line:

this.map.on('pm:create', e => {

I expect I'm missing something simple. My basic questions boils down to: How do you listen for an event on an object property?


Solution

  • In the wrong place

    You're using a class so you could do:

    class EditMap {
      constructor(map) {
        this.map = map;
    
        this.map.on('pm:create', this.pmCreate)
      }
    
      pmCreate(e) {
        console.log('Feature created');
      }
    }
    

    or simply this; but will fill out quickly as you add other listerners:

    class EditMap {
      constructor(map) {
        this.map = map; //Leaflet map
    
        this.map.on('pm:create', e => {
          console.log('Feature created');
        });
      }
    }