Home arrow JavaScript arrow Page 4 - Interactive Effects

The Dojo Event System and the Target Object - JavaScript

If you're looking for a quick way to delight your visitors with the addition of Ajax to your site, look no further. This article, the first part of a four-part series, will show you how to do some very nice interactive effects. It is excerpted from chapter four of Adding Ajax, written by Shelley Powers (O'Reilly, 2007; ISBN: 0596529368). Copyright 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Interactive Effects
  2. Ajax-Friendly Event Handling
  3. Mashable Event Handling
  4. The Dojo Event System and the Target Object
By: O'Reilly Media
Rating: starstarstarstarstar / 7
September 20, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Most Ajax libraries provide some form of event handling functionality. For instance, the Dojo library includes the Dojo Event System, which simplifies event handling considerably--simplifies and adds its own little tricks.

In Dojo, to support the same functionality as in our last section--that is, to attach an event listener to catch the window load event and the clicks for the two div
elements--all you need to do is use the connect method for the dojo.event object:

  dojo.event.connect(obj,"onclick",eventHandler);

It's similar to the function shown in Example 4-1, except that Dojo's event system goes beyond the simple manageEvent. For one thing, Dojo manages browser differences when it comes to passing the event object to the function. Though not
demonstrated in Example 4-1, typically if you want to access the event object in an event handler, and do so in a cross-browser manner, you must use code similiar to the following in the first line of the event:

  function eventHandler(evnt) {
    
var event = evnt || window.event;
  ...
  }

Or:

  function eventHandler(evnt) {
    
var event = evnt ? evnt : window.event;
  ...
  }

If the event object passed to the evnt method exists, that object is assigned to the event variable; otherwise, you can get the event object from the window object. This is, again, a technique to make the functionality compatible with IE 6.x and 7, which doesn't pass the event object to the event handler function automatically.

With the Dojo event system, the library handles this for you, so you can assume you'll always have the event object as a parameter in the event handler. Example 4-2 shows a modified version of Example 4-1, using Dojo and the event object.

Example 4-2. Event handling  a la Dojo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Event Listening</title>
<style type="text/css">
#inner
{
  
background-color: #00f;
  
height: 100px;
  
width: 400px;
}
#outer
{
  
background-color: #ff0;
   padding: 10px;
   width: 400px;
}
</style>

<script type="text/javascript" src="dojo/dojo.js">
</script>

<script type="text/javascript">
//<![CDATA[

dojo.require("dojo.event.*");

dojo.event.connect(window,"onload",
                   
function setUp() {
   dojo.event.connect(document.getElementById('inner'),"onclick",clickHandler);
   dojo.event.connect(document.getElementById('outer'),"onclick",clickHandler);
   });

function clickHandler(evnt) {
  
alert(evnt.currentTarget.id);
}
//]]>
</script>

</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
</body>
</html>

In this example, the identifier of the element is accessed through the event object rather than through the object context, represented by this. The advantage to this approach is that the use of the event object is cross-browser compatible. If you use this.id with a browser like IE 7, you'll get a value of undefined rather than the identifier for the object that was impacted by the event.

If you want to stop listening to an event, use dojo.event.disconnect, using the same parameters you used with connect.

Of course, including Dojo just to do simple event management is equivalent to using a machete to open a package of bologna: it's serious overkill. However, the example does demonstrate that when using an external Ajax library, you're going to want to look to see whether it has event handling, and if so, use it rather than your own library. The main reason is to ensure compatible event handling between the external library and your application code as much as possible.

There's another reason I picked Dojo to demonstrate using packaged event management. Dojo goes beyond just handling cross-browser differences with events--it also provides a way of extending the event system so that you can attach invocation event handlers to the functions themselves. These invocation event handler functions are called when their associated functions are processed.

The reason for such an extension is that Dojo, unlike many other Ajax libraries, has an infrastructure that is meant to be built upon via plug-ins, all of which coexist with the library. The other libraries are architectures on which applications are built. If a new Dojo plug-in has a function that has to be called whenever another Dojo function is called, it subscribes to that function.

The web page in Example 4-3 consists of the same two div elements in Examples 4-1 and 4-2. In Example 4-3, though, when the inner block gets a click event, the inner block's color is changed. When this happens, we also want to change the color of the outer block. In the application code, a new object is created with two methods, change1 and change2, which change the inner and outer blocks, respectively. The application uses the Dojo event system to register the first object method, change1, as an "event publisher," assigning it the topic name of "/example". The code then uses the dojo.event.topic.subscribe method to add a subscriber to this new topic publisher, so that when the first method, change1 fires, the second object method, change2, also fires.

Example 4-3. Exploring publisher/subscribe in the Dojo Event System

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Event Listening</title>
<style type="text/css">
#inner
{
  
background-color: #00f;
  
height: 100px;
  
width: 400px;
}
#outer
{
  
background-color: #ff0;
  
padding: 10px;
  
width: 400px;
}
</style>
<script type="text/javascript" src="dojo/dojo.js">
</script>

<script type="text/javascript">
//<![CDATA[

dojo.require("dojo.event.*");

var connObj = {
   change1 : function () {
             document.getElementById('inner').style.backgroundColor="#ff0000";
            },
   change2 : function () {
             document.getElementById('outer').style.backgroundColor="#ff00ff";
            }};

dojo.event.topic.registerPublisher("/example", connObj, "change1");

dojo.event.topic.subscribe("/example", connObj, "change2");

dojo.event.connect(window,"onload", function() {
    dojo.event.connect(document.getElementById('inner'),"onclick",connObj.change1);
   });

//]]>
</script>

</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
</body>
</html>

When accessing the example page and clicking on the inner block, its color is changed from blue to red, as you would expect because of the event handler function assigned directly to the click event for the block. However, the outer block's color also changes from yellow to magenta because of the topic publisher/subscriber functionality added through the Dojo event system. It's a simple demonstration of a very powerful functionality--one that is created specifically for extending Dojo with custom widgets.

It's an intriguing infrastructure, and one to be aware of if using Dojo. Additionally, keep it in mind for your own libraries if you need this type of pluggable infrastructure.

Now, on with the Ajax interactive effects.

Please check back next week for the continuation of this article.



 
 
>>> More JavaScript Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

JAVASCRIPT ARTICLES

- Javascript for Beginners: An Introduction
- Introduction to JavaScript
- Adding Elements to a Tree with TreeView jQue...
- Using the Persist Argument in a TreeView jQu...
- Using Unique and Toggle in a TreeView jQuery...
- Using Event Delegation for Mouseover Events ...
- Using the Animate Option in a Treeview jQuer...
- Using HTML Lists with Event Delegation in Ja...
- Opened and Closed Branches on a TreeView jQu...
- Mouseover Events and Event Delegation in Jav...
- Creating a TreeView JQuery Hierarchical Navi...
- Event Delegation in JavaScript
- A Look at the New YUI Carousel Control
- Working with Draggable Elements and Transpar...
- Displaying Pinned Handles with Resizable Con...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: