2015-10-05 66 views
1

如何暂时禁用viewchangeend事件,使用setView方法更改视图并再次重新启用viewchangeend事件?暂时禁用“viewchangeend”事件

这里是什么,我现在做的轻型版本:

var mapEventsObjects = []; 

/* Remove map events */ 
for (var i = 0; i < mapEventsObjects.length; i++) { 
    Microsoft.Maps.Events.removeHandler(mapEventsObjects[i]); 
} 

/* Change the view */ 
map.setView({ 
    "zoom": zoom, 
    "center": new Microsoft.Maps.Location(lat, long) 
}); 

/* Add map events back */ 
var mapViewChangeEnd = Microsoft.Maps.Events.addHandler(map, "viewchangeend", function (e) { 
    console.log("viewChangeEnd Fired: ", e); 
}); 

mapEventsObjects.push(mapViewChangeEnd); 

我想到的是看到没有viewChangeEnd在控制台被解雇,但它似乎有不是一次,而是两次。

任何想法为什么它不工作?

回答

0

您可以创建一个简单的布尔变量gobal。如果您想忽略viewchangeend事件,请将该变量设置为true。然后,在viewchangeend事件的事件处理程序中,可以执行简单检查,如果此变量为true,则将该变量设置为false并离开该函数。以下是您的代码的修改版本:

var mapEventsObjects = [], skipViewChangeEnd = false; 

//Add view change end event to map. 
var mapViewChangeEnd = Microsoft.Maps.Events.addHandler(map, "viewchangeend", function (e) { 
    //Check to see if you want to skip this event once. 
    if(skipViewChangeEnd){ 
     skipViewChangeEnd = false; 
     console.log("viewChangeEnd skipped"); 
    }else{ 
     //Your logic for handling this event 
     console.log("viewChangeEnd Fired: ", e); 
    } 
}); 

mapEventsObjects.push(mapViewChangeEnd); 

skipViewChangeEnd = true; 

/* Change the view */ 
map.setView({ 
    "zoom": zoom, 
    "center": new Microsoft.Maps.Location(lat, long) 
}); 
+0

我需要在调用'setView'之前临时禁用事件,然后重新启用它。由于JS的异步特性,如果我将该变量设置为true,则调用'setView'并将其重新设置为false,在调用'setView'时它将为false。 – Mahdi

+0

不,它不会。在setView调用已经触发并且地图移动完成之前它不会被设置为false。之前我已经多次使用过这种方法。 – rbrundritt

+0

你永远不会重新启用该事件。在调用'setView'后,你必须将'skipViewChangeEnd'设置为'true',所以它将继续正常工作。但是,如果你这样做,它会在'setView'完成之前设置为'true',因此让事件再次触发。 – Mahdi