« Back to FrontPage

Client-side Inter-Portlet-Communication (IPC) using Java Script

Preface - Even if there is already another article about IPC using Java Script, I add another one, because the mentioned article is very long, uses not useful examples, and contains some errors that cost me several hours ^^.

There are two ways IPC can be realized: server side and client side. As stated in the title, this article is about the client side implementation using Java Script. To do this, Liferay's native Java Script API provides a very useful event bus system: one can send an event (a tuple consisting of an event name and parameters) into the bus and on another place one can react to this event. Since this bus system is portlet cross border, one can react on an event within the same portlet or in any other portlet. There are two static methods one can use: fire to fire an event into the bus combined with optional parameters, and on to react on an event in the bus using the optional parameters. The parameters are interchanged following the key/value format.

Following the example code


// IN PORTLET 1
// Send the event 'siteWideUniqueEventName' to the bus
Liferay.fire(
   "siteWideUniqueEventName",
   {
      paramKey1 : "paramValue1",
      paramKey2 : 42,
   }
);

// IN PORTLET 2
// In portlet 2, react on the event using the
// first parameter
Liferay.on(
   "siteWideUniqueEventName",
   function(data) {
	alert("I'm portlet 2 and the value is" + data.paramKey1);
   }
);

// IN PORTLET 3
// In portlet 3, react on the event using the
// second parameter
Liferay.on(
   "siteWideUniqueEventName",
   function(data) {
	alert("I'm portlet 3 and do some calc: " + (2 * data.paramKey2));
   }
);

Since the Liferay object and its static methods fire and on are part of the aforementioned native Liferay Java Script API, you do not have to include any JS files.

0 Attachments
11829 Views
Average (1 Vote)
The average rating is 5.0 stars out of 5.
Comments