JQuery – Publish Subscribe Pattern

Posted: December 13, 2010 in Design Patterns, JQuery
Tags: , , ,

1. Using bind, trigger functions we can implement simple Publish/Subscribe pattern in JQuery
2. Below example shows how to create Subscribers (generally the script on page sections or modules) by subscribing to a common custom event called buttonClick through JQuery bind method and it also shows how to publish the custom event on some action (manual or automatic – here on click of button which is manual action) which intern fires all subscriber’s Action methods through JQuery trigger method.
3. There is already a plug-in available in JQuery site for achieving this by simply calling $.subscribe, $.publish and with few other functions. Refer http://www.dotnetoutsource.com/Download/jQuery/Publish-subscribe.aspx for sample. Our custom functions can be extended on top of native JQuery code using Plug-ins to access them directly on $ operator, like $.subscirbe.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.js“></script>
<script language=”javascript”>
    // Publisher script can be at page level. Actual publish action will be invoked through either user actions or through callback functions in case of ajax calls
    var Publisher = {
        Publish: function (eventName, args) {
            $(document).trigger(eventName, args);
        }
    };

    // Subscriber1/Subscriber2 can be part of page sections i.e. user controls (in case of asp.net page)
    var Subscriber1 = {
        subscribe: function () {          
            $(document).bind(‘buttonClick’, Subscriber1.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber1.subscribe();

    var Subscriber2 = {
        subscribe: function () {           
            $(document).bind(‘buttonClick’, Subscriber2.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber2.subscribe();

    $(document).ready(function () {
        // Binding publish method for button click event
        $(‘#myfield2’).unbind(‘click’).bind(‘click’, function () { Publisher.Publish(‘buttonClick’, [‘1’, ‘2’, ‘3’]); });       
    });
</script>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s