Jun 13, 2013

IPC using client side java script


  • Introduction

    The client-side mechanism to communicate portlets is based on events,uses events instead of direct js calls accross portlets is very important
    since it's not possible to know at deployment time which other portlets will be available in a given page.

    By firing/triggering an event one portlet just notifies that something has happened,
    and then one or more of the other portlets in the page might be listening and act accordingly.

    Code snippet:

    Example: Updating a label inside second-portlet using a link provided in the first-portlet.

    snippet-1: insert the below code in to docroot/view.jsp of first-portlet.

    <script>
    jQuery(
            function () {
              jQuery('a.change_label').click(
                function(event) {
                  Liferay.fire('changeLabel');
                  return false;
                });
              jQuery('a.remove_label').click(
                function(event) {
                  Liferay.fire('removeLabel');
                  return false;
                });
           }
    );
    </script>
    <a class="change_label">Click here to fire event</a><br/>
    <a class="remove_label">Remove label on second portlet</a>


    snippet-2: insert the below code in to docroot/view.jsp of second-portlet.

    <script>
            Liferay.on(
               'changeLabel',
               function(event) {
                 jQuery('label.info_label').html('Event fired on first-portlet');
               }
            );
            Liferay.on(
               'removeLabel',
               function(event) {
                 jQuery('label.info_label').html('');
               }
            );
                  
    </script>
    <br/><label class="info_label" />

    Deploy these portlets and check how they work.

    Congratulations !!

    NOTE:

     Liferay.trigger(eventName, data)
     Liferay.bind(eventName, function, [scope])
    These methods have been deprecated in Liferay 6 in favor of
     Liferay.fire(eventName, data)
     Liferay.on(eventName, function, [scope])

     For more Information about this please check this link