Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Create reusable and redistributable components with Dojo and AJAX

Manish Kataria (mkataria@in.ibm.com), System Software Engineer, IBM
Manish Kataria
Manish Kataria works for IBM ISL on the Lotus Connections Activities Team.

Summary:  In this article, learn to use Dojo and Ajax to develop reusable components that can easily be integrated with core applications. A a step-by-step example shows how to develop a Web application that adds mailing capabilities to an existing blogging application, generates mailing widgets, and handles intricacies of cross domain communication.

Date:  10 Jun 2008
Level:  Intermediate
Also available in:   Chinese  Japanese

Activity:  9304 views
Comments:  

Introduction

Adding function to an existing application is arguably one of the most challenging efforts in software development. You have to be careful not to alter existing code and also ensure that your change satisfies any ease-of-use and performance requirements. In this article, learn how to introduce new functions at the later stages of a Web project and how to seamlessly integrate your changes with the existing project.

The method in this article is especially useful during the following stages in the software development life cycle.

  • Development stage. A client asks the development team to integrate new functions that would improve the usability of the product. (As projects start using iterative and agile methods of development, this is becoming more common.) A quick analysis and integration of new functions is required, with short turnaround time, without compromising the robustness and standards of the application.
  • Maintenance stage. Frequently involves the addition and removal of functions. The development team might also be required to plug out or plug in certain functions for a particular client. Other customizations are often required.

After reviewing the problem statement, the team should develop a flexible architecture that allows additions and removals without changing the code that deals with the core functions of the product or application. Ideally, code pertaining to core functions should not change at all because of the time already invested in testing and stabilizing that portion of code. The use case in this article shows how you can develop such an application and outlines some of the challenges.


Use case

A blogging application is up and running. The client has a new requirement to add a mailing function to the blogging system. The client has a mailing server in place and wants to somehow integrate the two applications. The client wants:

  • To provide users with a window whenever they click over a valid URL.
  • The window to include all the options provided by a mailing widget.
  • The mailing window to post messages to the mailing server.

Challenges

The development team cannot risk changing the core functions of the blogging system to add the mailing function. The situation was aggravated when the team, when developing core functions, used third-party software that does not allow them to make changes in the source code. In addition, management is resistant to altering the existing presentation and business layers.

Solution

There are two approaches available to the development team. Figure 1 shows the approach where core and new functions are not tightly integrated; the architecture has new functions loosely coupled with the core functions:


Figure 1. Core and new functions not tightly integrated
An approach where core and new functionality are not tightly integrated

Figure 2 shows the approach with core and new functions tightly integrated; in this architecture, new functions become an inherent part of the core functions.


Figure 2. Core and new functions tightly integrated
An approach where core and new functionality are tightly integrated

The development team decides to adopt the first approach, in Figure 1. It has all the benefits related to loosely coupled architecture, such as code reusability, and it also limits the testing effort required.

Dojo

Dojo, or the Unified toolkit, is an open source DHTML toolkit written in JavaScript. Dojo lets you easily build dynamic capabilities into Web pages and any other environment that supports JavaScript sanely. Use the components that Dojo provides to make your Web sites more usable, responsive, and functional. You can build degradable user interfaces easily, prototype interactive widgets quickly, and animate transitions. You can use the lower-level APIs and compatibility layers from Dojo to write portable JavaScript and simplify complex scripts. Dojo provides multiple points of entry, interpreter independence, forward-looking APIs, and focuses on reducing barriers to adoption. Resources has more information.

They will use the Dojo toolkit to develop widgets and integrate them with the main application in a loosely coupled fashion. They chose Dojo because:

  • It's a JavaScript based toolkit that meets the requirement for ease of integration. Just by including the JavaScript, they have the benefit of a rich API that should suffice for most of the development efforts. It allows the team to develop wonderfully rich and great-looking widgets with little or no effort to integrate them within the application.
  • Dojo supports Ajax, which makes the application more responsive and improves the overall efficiency. More importantly, it allows very fast interaction with the main application.

    If you are new to Ajax, it is a Web development technique used for creating interactive Web applications. It makes Web pages seem more responsive by exchanging small amounts of data with the server, behind the scenes, so the entire Web page doesn't have to reload each time the user requests a change. This is intended to increase the Web page's interactivity, speed, function, and usability. See Resources for more about Ajax.

Adding a Dojo widget

First, you need to set up Dojo (see Resources for help with setup). After setting up Dojo:

  1. You need to create a .js file that will include most of the coding effort. To plug in the required functions, just include this .js file in the presentation layer (jsp, HTML, and so on).
  2. To avoid including Dojo libraries in the presentation layer, include them in the .js file created in Step 1. Listing 1 shows sample code to enable the inclusion of dojo.js:

    Listing 1. Enabling inclusion of dojo.js
                            
    function addOnJsFiles(file)
    {
    	var scriptTag= document.createElement('script');
    	scriptTag.src  = file;
    	scriptTag.type = 'text/javascript';
    	scriptTag.defer = true;
    	document.getElementsByTagName('head').item(0).appendChild(scriptTag);
    }
    
    /*Take special care that you have not included the dojo.js in the jsp also, as this
     is known to cause problem in IE though it works fine with Firefox. If  you have 
     included both dojo.js and the .js file in which this function is to implemented, 
     you should remove inclusion of dojo.js from jsp file.*/
          

    Depending on the directory structure, you might have to make a call to Listing 1, as shown in Listing 2:



    Listing 2. Call to function in Listing 1
                            
    addOnJsFiles('js/dojo/dojo.js');  
    /* Take care of the directory structure */
    	

  3. A parsing mechanism lets you find any e-mail addresses on the screen being visualized by the user. You can use JavaScript's regular expression to do this, as shown in Listing 3:

    Listing 3. Searching all valid e-mail patterns
                            
    var email = /(([a-zA-Z0-9_\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)/g
    		

  4. Write the code snippet that allows you to wrap up the e-mail address in a label tag, as shown in Listing 4:

    Listing 4. Replacing all the valid e-mail patterns
                            
     var htmlContent = document.body.innerHTML;
     htmlContent=htmlContent.replace(email, "<label onclick= 
        "sendmail('$1')\">$1</label>");
     document.body.innerHTML=htmlContent;
     		

  5. Use the sendmail function to include the primary business logic and the code for creating and displaying Dojo widgets. Include the files that you need for your widgets, depending on which widgets and APIs you use. Listing 5 shows an example:

    Listing 5. Include necessary packages
                            
    dojo.require("dojo.widget.*");
    dojo.require("dojo.event.*");
    dojo.require("dojo.widget.Button");
    dojo.require("dojo.widget.Editor2");
    dojo.require("dojo.widget.Textbox");
     		

    You'll have to include packages such as dojo.widget.* even though you include specific widget libraries (like dojo.widget.Button). This behavior is unlike Java and other languages. The method dojo.require will dynamically retrieve the JavaScript code and load them in the page. If you don't include dojo.widget.* and dojo.widget.Button, you'll get a run time exception because the common widget libraries wouldn't have been loaded.

  6. Dojo provides two approaches for creating widgets:
    • Pass the parent id of the widget in the constructor (showin in Listing 6). "Parent" here means the DOM element to which our widget will be connected.

      Listing 6. Creation of Dojo widgets
                                      
      var tmpDiv = document.getElementById(divid);
      var FloatingPaneWidget = dojo.widget.createWidget("FloatingPane", 
      	{ 
      		id:"pane1",windowState:"minimized",
      		title:"Send Email", hasShadow: "true", 
      		resizable:"true",displayMinimizeAction:"true", 
      		toggle:"explode",constrainToContainer: "false" 
      	},
      	tmpDiv);
      

    • Create widgets programmatically and insert them back into the DOM structure, as shown in Listing 7:

      Listing 7. Creation of Dojo widgets
                                      
      var newEditor = dojo.widget.createWidget('Editor2');
      var layoutWinEd2 = dojo.widget.createWidget("LayoutContainer",
         {layoutAlign:"top"});
      layoutWinEd2.addChild(newEditor);
      

      Listing 7 adds the editor to the layout container. To connect to our mailing widget, you can include the following code:

      FloatingPaneWidget.addChild(layoutWinEd2);

      For adding the business logic (actual code for sending e-mails), Dojo gives you the ability to attach their methods along with the primitive ones provided by the toolkit. Attaching a customized method is done with:

      dojo.event.connect(SubmitButtonId,"onClick", "codeForSendingMail");

      Write the function for handling the onclick event, shown in Listing 8:

      Listing 8. Sample code for handling events.

                                          
      function codeForSendingMail () {
      	alert("Special handling for onclick ...");
          ...Your logic goes here
       } 
      

    Finally, to display your widgets use:
    dojo.widget.byId('pane1').show();

  7. To submit data asynchronously, use the library dojo.io. This library provides a fairly simple interface for submitting the forms data asynchronously through the bind method. Listing 9 shows an example:

    Listing 9. Handling events
                            
    var myform = dojo.byId("myform");
    dojo.io.bind({
     url: xyz.com, 
     /* This is not required if the form has an action element defined */
     formNode: myform,
     method: myform.method,  /* Get or Post */
     load: myCallBackFuntion,
     error: function(type, error) 
     { 
    	alert("Error: " + type + "n" + error); 
     }	
    });
    	

  8. Dojo provides support for cross domain communication. Because the application requires communication across different domains (application server, mailing server), use Dojo's XhrIframeProxy library. Add the code in Listing 10 to the .js that you developed earlier.

    Include the dojo.io.XhrIframeProxy, which does all the Iframe work, to Dojo's bind function:

    dojo.require("dojo.io.XhrIframeProxy");



    Listing 10. Dojo's bind call
                            
    dojo.io.bind({
      IframeProxyUrl: http://externalDomain/myhtml.html,
      url:http://externalDomain/path/myservlet.do,
      content: 
      {
    	To:toVal, From: fromVal, CC: ccVal, BCC:bccVal, Subject: subVal, Message: 
    	   messageText
      },
      load: showSucessMessage,					
      error: showErrorMessage,
      method: 'POST',
      mimetype: "text/html"
    });
    		

    IframeProxyUrl is the location of the HTML file on the external domain, which includes a .js to implement the authorization (isAllowedRequest) function.

    The HTML file myhtml.html, on the domain externalDomain, should implement the function in Listing 11 by including a .js file or directly in script tags:



    Listing 11. Remote html should include
                            
    function isAllowedRequest(request){
    	/*
    		Return true if you want to allow cross domain interaction, 
    		else return false
    	*/
    }
    

Conclusion

In this article, you learned how to add a floating pane (Dojo widget) and integrate it back into the main application without altering the original code base. Advantages of this development strategy include:

  • Various teams can work on isolated parts of the project, allowing you to develop different modules in parallel. The framework of the methodologies allows for development and integration of independent and redistributable code.
  • Testing and acceptance efforts are reduced dramatically. Testers can focus only on new functions being integrated, rather than retesting an entire application.
  • Flexible customization according to business requirements. Add-on functions can be added or removed at any time.

Resources

Learn

  • Get a demo and learn all about Dojo.

  • Check out a collection of Dojo FAQs.

  • "Develop HTML widgets with Dojo" (Igor Kusakov, developerWorks, February 2007) shows the basics of developing HTML widgets using Dojo, including how to refer an image, how to add an event handler to an HTML page, and how to handle composite widgets.

  • Use the case study "Develop a Web application using Ajax with Dojo and DB2" (Leons Petrazickis, developerWorks, February 2007) to learn to quickly creating an elegant, responsive Web application using IBM DB2 9 for Linux, UNIX, and Windows, XQuery, PHP, and the Dojo JavaScript Framework.

  • "Build apps using Asynchronous JavaScript with XML (Ajax)" (Naveen Balani and Rajeev Hathi, developerWorks, November 2005) explains how to build Ajax-based Web applications — complete with real time validation and without page refreshes — by following the construction of a sample book order application.

  • Browse the technology bookstore for books on these and other technical topics.

Get products and technologies

  • Download IBM product evaluation versions and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

Discuss

About the author

Manish Kataria

Manish Kataria works for IBM ISL on the Lotus Connections Activities Team.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=312871
ArticleTitle=Create reusable and redistributable components with Dojo and AJAX
publish-date=06102008
author1-email=mkataria@in.ibm.com
author1-email-cc=