Inter-Fragment Communication Using the JavaScript Event Bus
The concepts in this section are important, but the code described here will no longer work!
I do suggest reading it, but don't try running the code...
The fact that we are writing reusable page fragments, rather than whole pages, is very powerful, and will lead to lots of flexibility and code reuse across the OpenMRS ecosystem. But it also means we need to introduce a new (more complicated) paradigm for having fragments communicate with each other. For example, we've just built a fragment that shows a list of encounters. The UI Library module includes a fragment that can use ajax to load a preview of an encounter that you select on a page. Clearly, these two fragments are very useful when combined. But at the same time, neither one of them should depend on the other, since they are both perfectly functional alone, and they can both be used with other fragments too. So in order to make our fragments as flexible and reusable as possible, we need to "decouple" them.
The UI Framework includes a mechanism (based on the javascript event bus PageBus) that allows fragments to publish and subscribe to messages, and pass content with those messages.
First, you need to download and install version 1.0 of the UI Library module from the OpenMRS module repository here. (Do get version 1.0 for this tutorial, since we make no promises that the widgets it contains won't change in later module versions. For actual usage, you'll want the latest version.)
To demonstrate that functionality, we are going augment our encountersToday fragment so that it publishes an "encounterSelected" message when you click on one of the listed encounters. Later we'll play around with a couple things we can do with this message.
Edit yourmodule/omod/src/main/webapp/pages/helloWorld.gsp to add one line to the top:
<% ui.decorateWith("standardPage") %>
This decorator is provided by the UI Library module, and it includes standard js and css that the widgets provided by the module depend on.
Now, we can edit the encountersToday.gsp fragment (omitting the refresh button and ajax for simplicity)
<%
def id = config.id ?: ui.randomId("encountersToday")
def props = config.properties ?: ["encounterType", "encounterDatetime", "location", "provider"]
def showSelectButton = config.showSelectButton ?: false
%>
<table id="${ id }" class="decorated">
<thead>
<tr>
<% if (showSelectButton) { %>
<th></th>
<% } %>
<% props.each { %>
<th>${ ui.message("Encounter." + it) }</th>
<% } %>
</tr>
</thead>
<tbody>
<% if (encounters) { %>
<% encounters.each { enc -> %>
<tr>
<% if (showSelectButton) { %>
<td>
<a href="javascript:publish('${ id }.encounterSelected', ${ enc.id })">
<img src="${ ui.resourceLink("uiframework", "images/info_16.png") }"/>