如何以编程方式触发 select 事件

How to fire select event programmatically

我想以编程方式触发 select 事件,但我不知道如何操作。所以,这就是我创建 select离子相互作用的方式:

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

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

在我代码的其他部分,我将新功能推送到 selection:

selection.getFeatures().push(new_feature);

我想要的是触发select事件。我该怎么做?

不应该手动触发该事件。应该由交互本身来触发它。相反,我会做的是听不同类型的事件。

ol.interaction.Select 有一个特征集合,即 ol.Collection。当交互自己选择功能时,该对象会触发 addremove 事件,即通过其自己的处理程序的结果, 通过那些手动 pushed/removed.

这是一个片段:

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

这需要更多的管理,因为回调方法 每个功能 ,但最终你可以做你想做的事。