Some situations may require developers to call multiple methods on occurrence of an event. When we do know what all methods needs to be called before hand, then we could hard code ‘the set of methods’ that needs to be called. However, what if we do not know ‘the set of methods’ upfront?
In C# we may accomplish this using Multi-cast Delegate, Observer Pattern, a subset of Publish/Subscribe Pattern. So, how are we going to deal with this issue in JavaScript?
In scenarios where you know ‘the set of methods’ before hand, we can do call them as show below (see a live demo page)
To do the same stuff in a decoupled fashion, where you don’t know ‘the set of methods’ before hand, I solved the issue by implementing publish / subscribe pattern through EventManager class in JavaScript. The code listed above can be modified to use publish (when btnSubmit button is clicked) and subscribe (when chkSubscribe check boxes are checked ) feature as illustrated below (see live demo page)
$(document).ready(function () { $('#btnSubmit').click(function () { EventManager.Publish('onPublishFormSubmitEvent', $('#txtName').val(), $('#txtMessage').val()); }); $('#chkSubscribe1').change(function () { if ($(this).attr('checked')) { EventManager.Subscribe('onPublishFormSubmitEvent', onSubscribeFormEvent01); } else { EventManager.UnSubscribe('onPublishFormSubmitEvent', onSubscribeFormEvent01); } }); $('#chkSubscribe2').change(function () { if ($(this).attr('checked')) { EventManager.Subscribe('onPublishFormSubmitEvent', onSubscribeFormEvent02); } else { EventManager.UnSubscribe('onPublishFormSubmitEvent', onSubscribeFormEvent02); } });
With this approach, while publishing the btnSubmit button doesn’t need to know what all check boxes are subscribed. The whole logic of calling / notifying the event to the subscribers is done through EventManager Class, which maintains a Registry of events and ‘the set of methods’ to be called for each event.
You may download the complete source for the code from here