Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple pubsub with jQuery

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

The following works:

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

And later:

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

Obviously a real jQuery pubsub plugin would be trivial to install - I'm really looking to see:

  • Are there any hidden caveats?
  • Is this acceptable to get away with in StackOverflow examples to demonstrate event-driven behavior without confusing the OP by including some plugin code?
like image 924
philwinkle Avatar asked Feb 28 '14 22:02

philwinkle


1 Answers

If your use case is simple enough - go right ahead:

You can use it on arbitrary objects

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

Note that if you're using it on the document, you're effectively creating a global hidden dependency. Also, rolling your own pubsub for the client-side is ~20 LoC so that's another consideration since a jQuery dependency isn't something you'd always want to have.

like image 160
Benjamin Gruenbaum Avatar answered Nov 12 '22 00:11

Benjamin Gruenbaum