Basic Object

Deep thoughts on web programming

Custom Ember Leaflet 2.0 Components

Ember Leaflet is an incredibly powerful and well-designed addon for Ember 1 and 2. Miguel Andrade did a fantastic job of updating the original project for Ember 2.0 and writing some great documentation. The documentation does not, however, cover extending components and modifying their event listeners. Here are some tips for dealing with those issues.

New Locations for Addon Components

All of the layer components that were in the ‘layers’ directory of the addon in the first version are now in the ‘components’ directory. Your import statement goes from:

1
import MarkerLayer from 'ember-leaflet/layers/marker';

in the first version of Ember Leaflet to

1
import MarkerLayer from 'ember-leaflet/components/marker-layer';

in the latest version.

Overriding Event Listeners for Custom Components

There’s no officially supported way to override event listeners in this new version of Ember Leaflet, but, as Alex Grant pointed out in a GitHub issue, there is an undocumented way to do this - write a function whose name corresponds to a Leaflet event prefixed with an underscore. So:

1
2
3
_click(e) {
  alert('You just clicked a marker!');
}

This works because of the way that Ember Leaflet assigns event listeners to each component’s underlying Leaflet object when the component is initialized. There are more details about this in the aforementioned issue.

Accessing a Component’s Leaflet Object

While you can add another event listener using the underscore method described above, removing the default behavior requires accessing the component’s underlying Leaflet object. This object is the component’s _layer property, and it’s created when Ember Leaflet calls the component’s layerSetup() function.

I was able to remove a default event listener of the Leaflet object by defining a layerSetup() function for my custom component and then using Ember’s _super() function to call the parent component’s function.

1
2
3
4
layerSetup() {
  this._super();
  this._layer.off('click');
}

The Beginnings of a Custom Marker

My goal in digging into this was to override the default marker click event only in a certain state. I haven’t yet worked out the details here, but I have at least sorted out extending the component, removing the default click event, and defining a new click event.

This is the basic jist of my custom component right now.

1
2
3
4
5
6
7
8
9
10
11
import MarkerLayer from 'ember-leaflet/components/marker-layer';

export default MarkerLayer.extend({
  layerSetup() {
    this._super();
    this._layer.off('click');
  },
  _click(e) {
    alert('You just clicked a marker!');
  }
});

Let me know if you have any ideas! I’ll update this post when I’ve finished that last step.