Simple pubsub with jQuery

Is there a reason why it would be against best practice to use jQuery trigger and on methods as a cheap and simple pubsub?

The following works:

 $(document).on('my:custom:event',function(){ alert('this is an event'); }); 

And later:

 $(document).trigger('my:custom:event'); //=> alerts 

Obviously, the real jQuery pubsub plugin will be trivial to install - I really look to see:

  • Are there any hidden reservations?
  • How acceptable is it to run away in StackOverflow examples to demonstrate event driven behavior without confusing the OP by including some plugin code?
+7
jquery publish-subscribe
source share
1 answer

If your use case is simple enough, go straight ahead:

You can use it on arbitrary objects.

 var obj = {};$(obj).on(...) . 

Note that if you use it in a document, you are effectively creating a global hidden dependency. In addition, renting your own pubsub for the client side is ~ 20 LoC, so there’s another consideration, since the jQuery dependency is not something you always would like to have.

+5
source share

All Articles