我有一个mobx反应,有条件地将layer.on({click})
函数映射到图层组。
reaction(
() => this.managingDates,
() => {
if (this.managingDates) {
this.mapStore.polygonLayer.eachLayer(layer => {
layer.on({
click: e => {
this.mapStore.setManagedParcel({
feature: e.target.feature,
bounds: layer.getBounds()
});
layer.setStyle({
color: "red"
});
}
});
});
} else {
this.mapStore.polygonLayer.eachLayer(layer => {
layer.on({
click: e => {
this.mapStore.setActiveParcel(e.target.feature);
layer.setStyle({
color: "yellow"
});
}
});
});
}
}
);
第一次这很好,但是当反应再次使用不同的参数触发时,而不是覆盖on click事件,第二个函数被添加(因此在点击时都会调用这两个函数)。
如何在添加新事件之前删除上一层。单击事件?
答案 0 :(得分:0)
在managingDates
发生变化时,不是添加/删除点击监听器,而不是每层在一个监听器中使用三元组?
@observer
class App extends Component {
@observable managingDates = false;
layerListeners = [];
componentDidMount () {
this.mapStore.polygonLayer.eachLayer(layer => {
const onClick = (e) => {
this.mapStore.setActiveParcel(e.target.feature);
layer.setStyle({
color: this.managingDates ? "red" : "yellow"
});
}
this.layerListeners.push(onClick);
layer.on('click', onClick);
});
}
componentWillUnmount () {
this.layerListeners.foreach(f => {
layer.off('click', f);
});
}
render () {
// ...
}
}