Pregunta

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?
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top