Adobe Flex ActionScript prevent model tainting
I have some values stores in my model. I need to create a copy of those values, make some changes, and then output those changes without affecting the model values.
var my_source:Array = model.something.source
v开发者_如何学Goar output:Array = new Array();
for each (var vo:my_vo in my_source) {
if (vo.id == 1) {
vo.name = 'Foo';
output.push(vo);
}
else if (vo.id == 21) {
vo.name = 'Bar';
output.push(vo);
}
}
return output;
So, this works fine, except that any changes that are made when looping through my_source also seems to affect model.something. Why do changes to the my_source array affect the model? How do I prevent this from happening?
I've mentioned how to do this in my blog, but short answer is use ObjectUtil.copy(). What you're trying to do isn't copying since Flash uses reference based objects, so you're only copying the reference to the other array. By using ObjectUtil.copy(), you're doing what's called a 'deep copy' which is actually recreates the object in a new memory location.
You are dealing with references to data, not copies of data. This is how ActionScript-3 (and many other languages) works.
When you create the my_source
variable, you are creating a reference to model.something.source
, which also includes all of the references to your model objects. Further, when you loop through the my_vo
objects, you are also getting a reference to these objects. This means that if you make changes to the object in this loop, you are making changes to the objects in the model.
How do you fix this? Inside your loop, you will need to make a copy of your object. I don't know what my_vo
looks like, but if you have any other objects in that object tree, they would be references as well, which would probably require a "deep copy" to achieve what you want.
The easiest way (but usually not the most efficient way) to achieve a "deep copy" is to serialize and de-serialze. One way to achieve this:
function deepCopy(source:Object):* {
var serializer:ByteArray = new ByteArray();
serializer.writeObject(source);
serializer.position = 0;
return serializer.readObject();
}
Then, in your loop, you can make your copy of the data:
for each(var vo:my_vo in my_source) {
var copy:my_vo = deepCopy(vo);
// act on copy instead of vo
}
精彩评论