Having just completed an article on Callbacks in ActionScript and having previously written about custom events in ActionScript I thought I would take a few minutes and contemplate on the difference between the two and when I see each being useful. Bear in mind that I still have only a small amount of experience in Flex and ActionScript. This is more of a straw man post than a definitive guide and I welcome thoughtful criticisms and comments.
Both callbacks and events allow us to respond to events, the difference is how and to an extent, how complex. Custom events are a bit more complex to code and maybe that is why I see callbacks as more useful on a day to day basis.
I see custom events being useful in situations like I presented in my post on them, discrete components that are designed to be generic. Custom events are great for that scenario and even though they are a bit more complex, writing generic code and reusable classes is more difficult. It is important to note however that I don’t think every class should be coded for re-usability. Because of the overhead costs of designing a class to be reusable, I think that developers should only design for re-usability when they can make a strong argument for it and can show a good chance that the code will be re-used. In those cases, taking the extra time to code custom events is the right thing to do in Flex.
Callbacks however, are much easier to code and therefore quicker to implement. They do, however require tighter coupling of the code. Tighter coupling is not necessarily a bad thing if it gets the job done and the developer understands the trade-offs. The obvious trade-offs being that the code will be more difficult to re-purpose and it may be more difficult to maintain in the future.
In the sample code I posted, I chose callbacks to update the interface because the class I was writing was specific to that particular application and I did not see that it had much usefulness beyond that specific application.
Custom events and callbacks serve an important but very similar function. When you choose one over the other depends on how much work you want to put into the code and how much re-use you expect to get out of the code in the future.
Until next time,
I <3 |<