In the big scheme of event han­dling, pub­sub achieves the same end result as if we had used cus­tom jQuery event han­dlers. However, the ben­e­fit of using pub­sub in this sit­u­a­tion is twofold:

  1. $.pub­lish and $.sub­scribe aren’t bound to any DOM ele­ments, which, as any­body who has ever had a web­page bog down due to too many event han­dlers can attest, is a pos­i­tive thing.

  2. Publishers and sub­scribers are loosely cou­pled, mak­ing it pos­si­ble to eas­ily define one or more sub­scribers to lis­ten for a topic with­out know­ing or car­ing what pub­lish­ers exist on a page. This pro­vides a mea­sure of free­dom in orga­niz­ing your code based more on sub­ject mat­ter of the action than sub­ject mat­ter of the source page.

    For exam­ple, we have sev­eral areas in the application where we allow users to cre­ate an audi­ence group, a process that is the same regard­less of trig­ger­ing event. Instead of hav­ing sep­a­rate event han­dlers for each page that allows group cre­ation, we could have a global sub­scriber for the topic “/group/add” stored in a util­ity file included on all pages, just wait­ing for that topic to be pub­lished, not car­ing if it’s com­ing from audi­ence main, cre­ate import, or the copy to groups dialog.

results matching ""

    No results matching ""