Linking two Google gadgets together
Gadget developers can build Google gadgets that communicate from one to another using Google’s publish subscribe framework API. One gadget can publish a message and another gadget can subscribe to it. For example, one Google gadget can offer choices to users and another Google gadget can process and display the selections to the user.
Google gadgets that communicate together on the dashboard must each be loaded into an import gadget and communicate on the same channel name.
The dashboard developer does not link the two import gadgets together because the Google gadget contains all the necessary code to publish and to receive the messages.
Listing 8‑3 shows an example Google gadget that publishes the current date to a custom channel when a user selects the HTML button.
Listing 8‑3 Example of a publishing Google gadget
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Sample PubSub Publisher">
<Require feature="pubsub"/>
</ModulePrefs>
<Content type="html">
<![CDATA[
Published date: <div id="output">...</div><br>
<script type="text/javascript">
function myEvent() {
var message=new Date();
gadgets.pubsub.publish("MY_CHANNEL_NAME", message);
document.getElementById('output').innerHTML = message;
}
</script>
<div>
<input type="button" value="Publish date and time" onclick="myEvent()"/>
</div>
]]>
</Content>
</Module>
Create a second import gadget using the code from
Listing 8‑2. Change the channel that the new Google gadget subscribes to so that it matches the channel name of the publishing Google gadget. In the previous example, the channel name was MY_CHANNEL_NAME. Change the subscribe method to use this channel name, as shown in the following code:
gadgets.pubsub.subscribe("MY_CHANNEL_NAME", onEventChange);
Add both Google gadgets to the same dashboard using Import Gadget. When the user selects the HTML button, the subscribing Google gadget receives the published message.
Figure 8‑5 shows the two gadgets communicating.
Figure 8‑5 Communicating between Google gadgets
The dashboard developer does not need to link the two import gadgets together because the Google gadget contains all the necessary code to communicate, to publish, and to receive the message.