Custom control - How can I allow the user to receive the 'change' event?

41 views
Skip to first unread message

ahalota

unread,
Feb 24, 2016, 5:19:05 PM2/24/16
to Leaflet
I built a custom control with a drop-down menu (<select>). Within the plugin's onAdd() function, I use this line:

L.DomEvent.addListener(mySelect,'change',this.onChange,this); 

to handle the change internally. This works fine, and with the added function I created onChange(), I do some preprocessing on a certain map layer. What I really want now is to pass this on so that the user can run something such as:

myControl.on('change', function(e){
   var newLayer = e.layer;
   ///do something with the new layer
});

Thanks for any help!

ahalota

unread,
Feb 25, 2016, 6:01:49 PM2/25/16
to Leaflet
I figured it out, although I'm not sure if this is a "good" way to do it. The .on() method I was looking for is from jQuery, so it's not there by default. I added it to my control like this:

L.Control.MyControl = L.Control.extend({ 
options:{....},
on: function(type, handler) {
 if (type == 'change') {
this.onChange = handler;
L.DomEvent.addListener(this.div,'change',this._onChange,this);
} else if (type == 'click') {
this.onClick = handler;
L.DomEvent.addListener(this.div,'click',this.onClick,this);
} else {
console.log('MyControl does not handle ' + type + ' events.');
}
},
_onChange: function(e) {
var newLayer = /*processing to get the layer I want to pass on*/;
e.feature = newLayer;
this.onChange(e); 
 }
}

The thought process is, once the user has requested an event listener with something like:
 
newControl.on('change',function(e){/*handle event*/});

only THEN do I add the event listener to the html element (in my case, "this.div"), and store the users method as the event handler. With the 'click' event, I didn't do any preprocessing, so this is just as a convenience to users. With the 'change' method, I actually set the event handler to be my private method, _onChange. Then, that method handles preprocessing, and passes it on to the user-defined handler function.

I know this isn't quite the right way to do it, but it works for now. I appreciate any better advice though. The biggest issue I see with this method is that unlike the jQuery system, where an event handler is active until 'off' is called on it, this stay on forever. So, perhaps most critically on 'off' event would be needed. Maybe next time....

BTW, I was making a CountrySelect plugin, now available on github: https://github.com/ahalota/Leaflet.CountrySelect/tree/master (demo)

 
 
 
 
 
 
 
 
 
 
 
Reply all
Reply to author
Forward
0 new messages