I've been looking over the internet for examples of implementing the observer pattern in jquery.
I would like to have it like this
observer1.observe(subject);
observer2.observe(subject);
Define some custom event callbacks for the observers
observer1.bind('customEvent', function(contextData) {
//Some code
});
observer1.bind('anotherCustomEvent', function(contextData) {
//Some code
});
observer2.bind('customEvent', function(contextData) {
//Some code
});
The following line would then trigger the customEvent callbacks of both observers
subject.trigger('customEvent', contextData);
while the following would fire anotherCustomEvent on observer1 only, since observer2 doesn't have that custom event binded
subject.trigger('anotherCustomEvent', contextData);
Guides on the internet is more general:
$( document ).on( "topicName" , function () {
//..perform some behaviour
});
$( document ).trigger( "topicName" );
(Example from http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjquery) I can't see how the above code can be used to accomplish what I'm looking for.
Either i would have to make it like this (if I keep it like the above example):
$(document).on("customEvent", function () {
observer1.trigger("customEvent");
observer2.trigger("customEvent");
});
$(subject).click(function() {
$(document).trigger("customEvent");
});
or a little bit better:
$(subject).click(function() {
observer1.trigger("customEvent");
observer2.trigger("customEvent");
});
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.
Have I misunderstood observer pattern or is there a way to achieve what I'm looking for?
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript 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.