Javascript function works not as intended when I move mouse too quickly. Ideas on how to improve?
I have a drag-and-droppable control on my page. It has a client-side event 'OnClientDragging' which I am using to provide highlighting to my page. The idea is that there are various zones on the page and, as the user drags the control over parts of the page, the page gets highlighted accordingly.
The problem is that I see the highlighting flicker slightly when moving fast. I do not see any exceptions being thrown, but if I move the mouse rapidly while staying inside of one 'zone' I still see the highlighting being removed and re-added. I can only assume this is because the method is not completing in time -- and fires again due to being dragged more.. which causes unintended issues?
function RemoveHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.removeCssClass("zoneDropOk");
}
}
function AddHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.addCssClass("zoneDropOk");
}
}
var previousZone = null;
//Evaluates whether the currently moused-over item is a RadDockZone.
function TryGetZoneFromTarget(target) {
while (target != null && target.id) {
if (target.id.indexOf("RadDockZone") != -1) {
return $find(target.id);
}
target = target.parentNode;
}
return null;
}
//Adds highlighting to the dockZones when the user is dragging objects to the screen.
//Clear the old dockZone as the user moves out of it, and color new ones as they move into it.
function OnClientDragging(sender, eventArgs) {
var target = eventArgs.get_htmlElement();
var zone = TryGetZoneFromTarget(target);
if (zone) {
var currentZone = zone;
dockZoneDroppedOnID = zone.get_id();
if (previousZone == null) {
previousZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
else if (previousZone != currentZone) {
$.queue(RemoveHighlighting(previousZone));
previou开发者_如何学运维sZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
}
else {
dockZoneDroppedOnID = "";
if (previousZone != null && $.queue.length == 0) {
RemoveHighlighting(previousZone);
previousZone = null;
}
}
}
Should I be trying to make this script more efficient, or maybe setting a variable outside the local scope to indicate that the previous event is still running and cancel the current event?
EDIT: I've edited in a queue solution which worked well! I'm not sure if it's a perfect solution, but it solved my issue.
I think setting variables outside this scope will be a more effective approach, in particular, you can either make use of or emulate the way jQuery's fx queue works.
精彩评论