문제

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?
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top