title: Jquery Observer pattern
body: <p>I've been looking over the internet for examples of implementing the observer pattern in jquery.</p>
  
  <p>I would like to have it like this</p>
  
  <pre><code>observer1.observe(subject);
  observer2.observe(subject);
  </code></pre>
  
  <p>Define some custom event callbacks for the observers</p>
  
  <pre><code>observer1.bind('customEvent', function(contextData) {
    //Some code
  });
  observer1.bind('anotherCustomEvent', function(contextData) {
    //Some code  
  });
  observer2.bind('customEvent', function(contextData) {
    //Some code  
  });
  </code></pre>
  
  <p>The following line would then trigger the customEvent callbacks of both observers</p>
  
  <pre><code>subject.trigger('customEvent', contextData);
  </code></pre>
  
  <p>while the following would fire anotherCustomEvent on observer1 only, since observer2 doesn't have that custom event binded</p>
  
  <pre><code>subject.trigger('anotherCustomEvent', contextData);
  </code></pre>
  
  <p>Guides on the internet is more general:</p>
  
  <pre><code>$( document ).on( "topicName" , function () {
    //..perform some behaviour
  });
  
  $( document ).trigger( "topicName" );
  </code></pre>
  
  <p>(Example from <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjquery" rel="noreferrer">http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjquery</a>)
  I can't see how the above code can be used to accomplish what I'm looking for. </p>
  
  <p>Either i would have to make it like this (if I keep it like the above example):</p>
  
  <pre><code>$(document).on("customEvent", function () {
    observer1.trigger("customEvent");
    observer2.trigger("customEvent");
  });
  
  $(subject).click(function() { 
    $(document).trigger("customEvent");
  });
  </code></pre>
  
  <p>or a little bit better:</p>
  
  <pre><code>$(subject).click(function() { 
    observer1.trigger("customEvent");
    observer2.trigger("customEvent");
  });
  </code></pre>
  
  <p>Either way I'm stuck with having to edit the subject-click-callback or document-customEvent-callback instead of telling the observer to subscribe to the subject.</p>
  
  <p>Have I misunderstood observer pattern or is there a way to achieve what I'm looking for?</p>
  
  <p><a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript" rel="noreferrer">http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript</a> mention Publish/Subscribe Pattern a bit further down in that chapter. That could be a way for me, but I'm missing the code behind the example.</p>