Jacobian
Jacobian

Reputation: 10802

How to fire select event programmatically

I want to fire select event programmatically, but I do not know how. So, this is how I create selection interaction:

var selection = new ol.interaction.Select({
    ...
});

selection.on('select', function (event) { 
    ... here is some action or event I want to trigger
});

In other part of my code, I push new features to the selection:

selection.getFeatures().push(new_feature);

What I want is to trigger select event. How can I do that?

Upvotes: 0

Views: 619

Answers (1)

Alexandre Dubé
Alexandre Dubé

Reputation: 2829

You should not fire that event manually. It should be up to the interaction itself to trigger it. What I would do instead is listen to a different type of event.

The ol.interaction.Select has a features collection, i.e. a ol.Collection. That object fires add and remove events when the interaction selects features by itself, i.e. by the result of its own handler, and by the result of those manually pushed/removed.

Here's a snippet:

var featuresCollection = selection.getFeatures();
featuresCollection.on('add', function() {
  // do what you want on add
});
featuresCollection.on('remove', function() {
  // do what you want on remove
});

This would require a little bit more management, as the callback method are fire per feature, but in the end you would be able to do what you want to do.

Upvotes: 2

Related Questions