4

From what I've understood ol.Object classes have observable properties which are detailed here: http://openlayers.org/en/v3.8.1/apidoc/ol.Object.html

This makes sense to me, however what is not detailed here is how to dispatch custom events on classes that extend the ol.Object.

In my current application I create controls that extend the ol.Control class and by definition are ol.Object's. So I can listen to changes to properties that I have set using ol.Object's get/set methods. I've also been able to see how events are dispatched by doing the following for example:

objectOne.dispatchEvent('fired');

I could then listen to his event and run a function accordingly:

objectOne.on('fired', function(e) { alert('fired!'); });

In my code at present I am performing these operations and everything is ok, providing I use the debug version of OL3. As soon as I change to the compiled version dispatchEvent is no longer available.

Why is this method hidden in the production version? Should I be using a different method to fire my own custom events? It seems strange at present that you can listen for events and property changes but you cannot fire your own custom events when using the compiled version of OL3

1

This was an indeed very useful feature exported. Maybe it was not intended, and the developers just "fixed" the code by hiding it in the recent versions. The feature was undocumented, and the change was also undocumented in the changelog. Currently it has an open issue on the GitHub repository of OpenLayers 3, which you can access here.

As a workaround, you can set a property on your object with set, and it fires a propertychange event with the changed property stored in the event object's key property. Example:

var myObject = new ol.layer.Vector();
myObject.on('propertychange', function (evt) {
    if (evt.key === 'myattribute') {
        alert('fired!');
    }
});
myObject.set('myattribute', 'somevalue');
  • 1
    Thanks for the response Gabor, I have used something similar to that shown in your comment for the time being, I'm checking directly on the properties though by using 'change:myattribute'. Hopefully the OL3 team will give us access to this function in the future or implement another way for us to dispatch our own events on objects that have extended the ol.Object class. – marlowp Aug 24 '15 at 15:22
  • Great shortcut! As an alternative solution, you can attach a listener to the object's change event, which only fires, if the revision counter goes up. The revision counter only goes up, when you call the object's changed() method. You can assign only one custom event on an object with this method, though. – Gabor Farkas Aug 24 '15 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.