JavaScript
  Home arrow JavaScript arrow Page 4 - Interactive Effects
CIO Insight
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Interactive Effects
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2007-09-20

    Table of Contents:
  • Interactive Effects
  • Ajax-Friendly Event Handling
  • Mashable Event Handling
  • The Dojo Event System and the Target Object

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Interactive Effects - The Dojo Event System and the Target Object
    (Page 4 of 4 )

    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.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the book "Adding Ajax," published by O'Reilly. We...
     

    Buy this book now. This article is excerpted from chapter four of Adding Ajax, written by Shelley Powers (O'Reilly, 2007; ISBN: 0596529368). Check it out today at your favorite bookstore. Buy this book now.

       

    JAVASCRIPT ARTICLES

    - Getting Attention with Interactive Effects
    - Interacting with Tooltips and Previews
    - Just-in-Time Information and Ajax
    - Interactive Effects
    - Using Cookies With JavaScript
    - Understanding the JavaScript RegExp Object
    - Controlling Browser Properties with JavaScri...
    - Using Timers in JavaScript
    - Form Validation with JavaScript
    - JavaScript Exception Handling
    - Stringing Things Along
    - Understanding The JavaScript Event Model (pa...
    - Understanding The JavaScript Event Model (pa...
    - An Object Lesson In JavaScript




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway