In the first part of this article I demonstrated using the basic Proxy functionality. Now we get to the fun stuff, which we need to support for..in and for each..in constructs.
//Gets the next index. When you return 0, for..in and for each..in will quit.
override flash_proxy function nextNameIndex(index : int) : int
{
if (index < propertyNames.length)
return index + 1;
return 0;
}
Here's where the Flex docs get kinda confusing :) The first thing the VM does when you're iterating your Proxy object with for..in or for each..in is call nextNameIndex(0). The docs tell you the input is zero-based, but that's not the case, 0 isn't "first", 1 is. So when flex asks for the "next name from zero" it's actually asking if there's a first name at all. If you've got more properties to iterate, return index + 1. Otherwise, return 0 and the loop will end.
Note that you don't *have* to return index +1. This is how ArrayCollection, ListCollectionView and the like implement filters. But that's another post :)
//Get name[i] where i is 1-based
override flash_proxy function nextName(index : int) : String
{
return propertyNames[index - 1];
}
//Get value[i] where index is 1-based.
override flash_proxy function nextValue(index : int) : *
{
return properties[propertyNames[index - 1]];
}
These two functions are the other half of the for..in and for each..in loops. After the VM gets the next index from nextNameIndex() it will call one of these two functions. In the case of for..in it will call nextName(), and for for each..in it will call nextValue(). Because we're not doing anything complicated in this example, we just return "properties[index - 1]" (remember Array is 0-based, the Proxy functions are 1-based). If there were more logic in our getProperty() method from the first part of this article, then we'd want to defer to that method rather than duplicate that login in the nextValue() method.
And that's how you use the Proxy class. Now, go build something bad-ass with it :)


0 comments:
Post a Comment