unbind不会'不起作用

unbind doesn't work

本文关键字:不起作用 不会 unbind      更新时间:2023-09-26

为什么我无法在openlayers 3中解除事件绑定?我试着画一个互动的圆圈。对于取消绑定事件,我使用map.un('click',function(){ ... });

M.on('click',function(e){
      if(!$pec.hasClass('active')) { deactive(true); return false;}
            if( !isDrawing ){
                isDrawing = true;
                var center = e.coordinate;
                var circle = new ol.geom.Circle([center[0],center[1]],10000,'XY');
                var feature = new ol.Feature(circle);
                var vectorSource = new ol.source.Vector();
                vectorSource.addFeature(feature);
                c = new ol.layer.Vector({
                    source: vectorSource
                });
                c.circle=circle;
                M.addLayer(c);
                $('body').css('cursor','crosshair');
            }
            else {
                isDrawing = false;
                deactive(false);
                $('body').css('cursor','default');
                finishDraw('circle',c);
            }
        });
        M.on('pointermove',function(e){
            if(isDrawing){
                c.circle.setRadius(distanceTo(c.circle.getCenter(),e.coordinate)); 
            }
        }); 
        function deactive(all){
            M.un('click',function(){ log('deactive click');});
            M.un('pointermove',function(){});
            if(c && all) M.removeLayer(c);
            isDrawing = false;
        }

如何解决?我有更多这样的解绑,一切都不起作用

我认为这里发生的事情是,绑定事件的方法是匿名的。当您想要解除事件绑定时,必须将相同的方法作为引用发送。

尝试将函数声明为变量,然后在绑定和取消绑定操作中都使用它。类似于:

var myFunc = function(e) {};
M.on('click', myFunc);
M.un('click', myFunc)

此外,函数本身在无界时不会被调用。这就是为什么你的日志不起作用。