Wednesday, September 3, 2008

Removing list items in AS2/AS3


Let's suppose, we have some kind of custom list, elements of which has UI representation. A big problem for the beginner developers is that when they remove the items from the list, some of them still stay there, on the stage, and function normal. They are being removed only after several remove function calls.
Here is a code snippet describing such a situation:


public class TestClass{
private var items:Array;
public function RemoveItems():void{
for (var i:int = 0; i < this.items.length; i++){
RemoveItem(this.items[i]);
}
}

public function RemoveItem(argItem:Item):void{
var tmpIndex:int = this.items.indexOf(argItem);
if (tmpIndex != -1){
this.items.splice(tmpIndex, 1);
}
}
}



This usually happens, when the developer has already written a RemoveItem function, which also removes some event handlers or cast appropriate events on Remove. And when the developer needs to clear the list he wish to use that function. That is right. But the thing here is, that using the first iteration in RemoveItems function we will only iterate through about the half of all the items. The indexer i will grow up, but the same time the length of the items list will decrease, removing each item from it.
Sometime this causes big problems.

The best way to avoid this situation, is to use non length-dependent iteration. That is, i.e. while.
So if we just change the for (...) with while (this.items.length > 0){... we will win.
Post a Comment