Question

I've seen the callback() concept used a lot in jQuery plugins and I'm starting to think triggering custom events could be a better alternative.

jQuery has a built-in mechanism to trigger('A_CUSTOM_EVENT') so why don't plugin authors simply trigger a 'COMPLETE_EVENT' rather than insist we pass in a callback function that is to handle this 'complete phase'.

Nick

Was it helpful?

Solution

This depends on what you are trying to achieve - it's an architectural choice.

Basically the event-paradigm is open, non-private and persistent. You have an public event, where everybody can register for, and their event functions are basically called as often as they wish until they unregister from the event. Makes sense for recurring events.

Example: Registering to a hover event.

The callback-paradigm is isolated, private and disposable. Someone calls your code and hands over a private callback, which will be disposed once it got executed. In most cases the usability is limited (limited to a single point in time) and/or should not necessarily be public.

Example: Handling an ajax response.

Both of these paradigms have advantages and drawbacks. Using one or the other is up to you and how you want your application to be used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top