Why it's important to override clone() in your custom Event class

The Flex API documentation says that you must override the clone method in your custom Event class. But you might have figured that, since the compiler didn't complain about the missing override, it wasn't really necessary.

Too bad the ActionScript language lacks a way to enforce this.

If you skip the override, it might just come back to bite you later in the form of a bug.

You probably never call clone directly in your code, but that doesn't mean it's never called. The clone method is called every time you redispatch an event.

When do you redispatch an event? A good example is the ComboBox component in the Flex framework. The component contains a TextInput object internally and dispatches the same enter event that it gets from that object. Similarly, the MenuBar redispatches some of the events it gets from its Menu object. There are several more examples of this in the Flex framework and the sample applications.

If you don't override clone, your custom Event won't be redispatched correctly. This could lead to a type coercion error if you're lucky. In worse cases, it might fail silently, leaving you pulling your hair for hours.

It should be noted that it's not just important to override clone, it's important to override it correctly and keep it up-to-date. If you add new properties to your Event class, you must make sure that you're copying those values over in your clone implementation.

Is that too much to ask? Yes, I think it is, and I think the language must evolve to make things easier in this respect, but more on that in another post.

2 Responses to “Why it's important to override clone() in your custom Event class”

  1. Haha very funny, I just encountered this bug this morning :)... It's those kind of recipes that will always scare people when learning Flex


  2. Thanks for explaining this out like you did. I always like learning more about the WHY.