Actions and filters are so awesome in WordPress. They provide a very simple and powerful way to customization the WordPress core. So, Plugins and themes can execute code before or after specified event or change the result of many core functions. On the web, I found few discussion about the Javascript porting of actions and filters.

jQuery triggerHandler approach

In my first experiment, I used the jQuery triggerHandler() featured in order to create something like add_action() as well as add_filter(). In other words, the do_action() becomes $( document ).triggerHandler( 'my_custom_event') and the add_action() becomes $( document ).on( 'my_custom_event', ... ).

However, this approach has some limit. First of all, is not possible to handle the priority feature: executing sequence. The function add_action(), in fact, supports the priority param in order to run an hook in a specified order. Also, triggerHandler() can return a result. This is great for “emule” add_filter() function but could make a mess.

Rewrite

This implementation is more beautiful and provide a more like experience of actions and filters in Javascript.

Benefits

  • A real stack/queue for actions and filters
  • Priority support for actions and filters
  • Arguments variable
  • Logical split between actions and filters

Have a look to an example of use below: