0

In the case of a browser event in OpenLayers, what exactly is the difference between:

select.on('select', function (event) {
    let selectedFeature = event.selected[0];
}

and:

select.on('select', function (event) {
    let selectedFeature = event.target.getFeatures().item(0);
}

select being an ol.interaction.Select instance.

Here's an output of such event on the console:
Browser console output of an event

They seem to give the same results at first glance.
Underlying this question, I also naturally wonder if one is better than the other, or not recommended.


As a background context, I first tried for hours to figure out why the following didn't work before finding that it did work with target instead of selected:

select.on('select', function (event) {
    let selectedFeature = event.selected.getFeatures().item(0);
}

From a natural language point of view, this latter makes the most sense to me.

I have found some info on the target (but I do not know if this relates to the same thing than in OpenLayers) at this URL; https://developer.mozilla.org/en-US/docs/Web/API/Event/target but I cannot find anything on the selected method/property.

2
  • 2
    selected is an array of the features which were selected in the event, getFeatures() includes those and any already selected. target is the object (the select interaction firing the event, so in your case event.target.getFeatures() is the same as select.getFeatures() but target is useful if you use the same handler for multiple interactions.
    – Mike
    Jan 24, 2021 at 22:31
  • 1
    @Mike I think your comment if of general interest and it should be put into answer.
    – TomazicM
    Jan 31, 2021 at 9:37

1 Answer 1

2

selected is an array of the features which were selected in the event, getFeatures() includes those and any already selected. target is the object (the select interaction) firing the event, so in your case event.target.getFeatures() is the same as select.getFeatures() but target is useful if you use the same handler for multiple interactions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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