Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator Written by: Chris Jaun (cmjaun@us.ibm.com) Sudha Piddaparti (sudhap@us.ibm.com) Objective In this tutorial you will create a Dojo application using the Web tools in IBM Rational Application Developer Version 8.0. Rational Application Developer provides wizards, content assist, validation, property views, palette drops, and other visual tools for rapidly developing Dojo web applications. Introduction You will build a Dojo-based loan payment calculator. The calculator accepts three pieces of input: loan amount, interest rate, and term. It outputs the monthly payment, a pie chart displaying the percentage of loan costs going towards principal and interest, and an amortization table. There is no submit button because the output fields are updated in real-time as users enter or change input. You will learn how to: Create a Dojo enabled Web application containing all of the resources required by your application Create a user interface using Dojo widgets Build your own custom Dojo widget Use content assist, templates, and wizards to rapidly write Dojo code and HTML Deploy your project to a server Create a custom Dojo build Debug web applications using Firebug In Part 1 you will set up a Dojo enabled project. In Part 2 you will use the Dojo Widget wizard, content assist, and palette drops to create a custom Dojo widget. In Part 3 you will create a web page containing a Dojo layout widget and your custom widget. You will also add the necessary output fields and Dojo code to activate them. In Part 4 (optional) you can add a pie chart to your page using the Dojo charting API. In Part 5 (optional) you can add a Dojo grid to your page using the palette. Part 6 (optional) contains information on creating custom Dojo builds. Part 7 (optional) contains information on integrated Firebug debugging support. - 1 -
Supporting Materials Rational Application Developer wiki: provides videos and articles to help you get started quickly with developing applications https://www.ibm.com/developerworks/wikis/display/rad/home Dojo Toolkit web site: provides a detailed Dojo reference guide and other information for getting started with Dojo. http://www.dojotoolkit.org/ - 2 -
Part 1: Project creation and setup Rational Application Developer provides a project setup wizard where you can customize how your application will access Dojo during development and at runtime. The simplest option (and the one used in this tutorial) is to have a copy of Dojo in your project and deploy it along with the rest of your project resources. Another option is to use a public Content Delivery Network (CDN), a remote server with a copy of Dojo. The use of CDNs are not covered by this tutorial, but they are simple to use, and you can learn more about them here: http://www.dojotoolkit.org/download/ 1. Start Rational Application Developer and select a workspace. 2. Close the Welcome tab. 3. Select File > New > Static Web Project to begin creating your application. 4. Enter LoanPaymentCalculator as the Project name. 5. To enable Dojo support, click the Modify button in the Configuration section. a. Expand the Web 2.0 node and select Dojo Toolkit. By enabling the Dojo Toolkit facet, your web project is configured to develop Dojo web applications. The Dojo Toolkit included in Rational Application Developer includes additional IBM extensions to the base Dojo Toolkit, including libraries for ATOM (ATOM Syndication Format) data access, analog and bar gauges, and simplified access for SOAP Web services. b. Click OK. 6. 7. 8. Click the Next button twice until you reach the Dojo Project Setup page. This page provides a summary of how Dojo will be incorporated into your project. By default, the latest Dojo supported by IBM is copied into your web project. At this point you can finish the wizard and move on to Part 2 of the tutorial. If you would like more information about the Dojo project setup options continue with the following optional steps. To modify the Dojo setup, click the Change these setup options button. - 3 -
a. The Dojo Project Setup Options dialog box provides you with three options for configuring Dojo in your web application. Select the third option, Dojo is remotely deployed or is on a public CDN, and click Next. b. You would use this option if your application uses a remotely hosted public CDN (content delivery network) or an existing copy of Dojo already deployed on your network. CDNs provide geographically distributed hosting for open source JavaScript libraries. When a browser resolves the URL in your Web application, the browser will automatically download the file from the closest available server. You will need to provide the URL or URI to the appropriate location. If Dojo is not contained in your project the tools must reference a corresponding copy of Dojo in order to provide content assist and validation. The wizard gives you the option of selecting a default version or selecting your own Dojo from disk. This option will not copy Dojo into your project or workspace. Click the Back button. c. Select the second option, Dojo is in a project in the workspace, and will be deployed from there, and click Next. d. On this page you can browse to the root Dojo folder in another project in your workspace. The copy of Dojo will not be copied into your project. It will be deployed from the project where it is currently located. Click the Back button. e. Select the first option, Copy Dojo into this project. It will be deployed from there, and click Next. f. On this page you can specify the location in your project where Dojo will be copied. At the bottom of the page you may select one of the default versions of Dojo shipped with Rational Application Developer or browse for a copy on your disk. Leave the default values and click Finish. 9. Click Finish in the project wizard. Your project is now created and appears in the Enterprise Explorer view. Under the WebContent folder you should see a folder named dojo that contains all the Dojo resources. If asked to switch to the Web Perspective, click Yes. - 4 -
Part 2: Creating a Custom Dojo Widget The Dojo toolkit includes dozens of standard widgets, including input fields, combo boxes and radio buttons. You can also create custom widgets to encapsulate reusable UI elements or a specific piece of functionality. Rational Application Developer provides a wizard to easily create new custom Dojo widgets. 1. 2. 3. 4. Right-click on the WebContent/dojo folder and select New > Dojo Widget. Enter LoanInput as the Widget Name. Enter loan as the Module Name. Leave the defaults for the rest of the fields and click Finish. - 5 -
5. Three files are created under a folder named dojo/loan: a templates/loaninput.html file that is the UI template for the widget a themes/loaninput.css file which provides the styling for the widget a LoanInput.js file which provides the JavaScript backend and business logic portion of the widget. Double-click LoanInput.js if the file is not already open. 6. 7. Change the widgetsintemplate field from false to true. This field indicates that our custom widget will contain other Dojo widgets as part of its UI. Directly below the widgetsintemplate field add three additional fields that will be used to hold the results of our calculation principal, interestpaid, and monthlypayment - they should all have default values of 0. Be sure to add a comma after each field. // Set this to true if your widget contains other widgets widgetsintemplate : true, principal: 0, interestpaid: 0, monthlypayment: 0, 8. Directly below the postmixinproperties function, add a new function named calculate. Leave the function empty for now. postmixinproperties : function() { }, // this function will perform the calculations for our loan payment calculate: function() { } - 6 -
9. Double-click templates/loaninput.html to open the file. 10. At the bottom of the editor click the Source tab to display the page in the source panea. 11. Within the existing div create three additional child div tags. You can use content assist by typing <d and then pressing CTRL-space. In the popup select <> div to insert the tags. 12. Within each new div tag add a text label Loan Amount:, Interest Rate:, and Term (years):. When complete your code should look like this: <div class="loaninput"> <div>loan Amount: </div> <div>interest Rate: </div> <div>term (years): </div> </div> 13. Now add Dojo widgets for each of the input fields. a. In the right-hand column, surface the palette by clicking the appropriate tab. You should see several drawers containing Dojo widgets. b. Expand the Dojo Form Widgets drawer by clicking on it. - 7 -
c. Select the CurrencyTextBox and drop it next to the Loan Amount label inside your div tag. d. Within the newly created input element type the letters cu and use content assist (CTRL + space) to bring up a list of attributes. Click on currency to insert it. e. Inside the currency attribute type USD. Your end result should look like this: <div>loan Amount: <input type="text" dojotype="dijit.form.currencytextbox" currency="usd"></div> f. Next, use content assist to insert the Dojo widget markup for the Interest Rate field. Put your cursor inside the second div tag after the label. Type <input d> and invoke content assist with your cursor directly to the right of the d. Click on dojotype to insert it. - 8 -
g. Inside the dojotype attribute invoke content assist again and you will see a list of available dojo widgets. Begin typing dijit.form.n until you see NumberSpinner. Click on it to insert into your page. h. Add the following attributes. You can use content assist to insert them the same way you added the currency attribute above. 1) value = 5 2) smalldelta =.05 3) intermediatechanges = true 4) constraints = {min: 0} <div>interest Rate: <input dojotype="dijit.form.numberspinner" value="5" smalldelta=".05" intermediatechanges="true" constraints="{min: 0}"> </div> i. From the palette drop a ComboBox Dojo widget into the Term (years) div. 1) Rational Application Developer provides additional configuration for some widgets when you drop them from the palette, such as the ComboBox. In the Insert Combo Box dialog box you can add values for your ComboBox. Add values for 1, 2, 3, 4, 5, 10, 15, 30. 2) Set 15 as the default selected value. - 9 -
j. Next you must add dojoattachpoint and dojoattachevent attributes to each of your input widgets. The value specified for the dojoattachpoint is the name that widget instance can be referenced by from the LoanInput.js file. The dojoattachevent attribute adds event handling to the widgets. 1) Using content assist add a dojoattachpoint attribute to each widget. Name them amount, rate, and term respectively. 2) For each widget add dojoattachevent= onchange: calculate. Every time an onchange event takes place on this widget it calls the calculate function you added to the LoanInput.js file. The final result of your html file should look like this: <div class="loaninput"> <div>loan Amount: <input type="text" dojotype="dijit.form.currencytextbox" currency="usd" dojoattachpoint="amount" dojoattachevent="onchange: calculate"></div> <div>interest Rate: <input dojotype="dijit.form.numberspinner" value="5" smalldelta=".05" intermediatechanges="true" constraints="{min: 0}" dojoattachpoint="rate" dojoattachevent="onchange: calculate"> </div> <div>term (years): <select dojotype="dijit.form.combobox" name="select" autocomplete="false" dojoattachpoint="term" dojoattachevent="onchange: calculate"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>10</option> <option selected="selected">15</option> <option>30</option> </select> </div> </div> 14. Save and close LoanInput.html and re-open LoanInput.js 15. Add dojo.require statements for the three widgets used in the html file. dojo.require statements load the necessary resources to create those widgets when the page is run. a. Below the existing require statements type dojo.re and invoke content assist (CTRL-space). b. Select dojo.require(modulename) from the popup. c. Type dijit.form.currencytextbox as the function attribute. d. Repeat steps b and c for dijit.form.numberspinner and dijit.form.combobox. //dojo.require the necessary dijit hierarchy dojo.require("dijit._widget"); - 10 -
dojo.require("dijit._templated"); dojo.require("dijit.form.currencytextbox"); dojo.require("dijit.form.numberspinner"); dojo.require("dijit.form.combobox"); 16. Now add the following code for the calculate function that you created earlier in Step 8. If you d like you can experiment with content assist. Note that standard JavaScript objects such as the Math object are available in content assist. The variables we defined earlier, principal, interestpaid, and monthlypayment are all available as well. // this function will perform the calculations for our loan repayment calculate: function() { this.principal = this.amount.attr('value'); if(this.principal == NaN) { this.monthlypayment = 0; this.principal = 0; this.interestpaid = 0; } else { var interestrate = this.rate.attr('value') / 1200; var terminmonths = this.term.attr('value') * 12; this.monthlypayment = Math.pow(1 + interestrate, terminmonths) - 1; this.monthlypayment = interestrate + (interestrate / this.monthlypayment); this.monthlypayment = this.monthlypayment * this.principal; } this.interestpaid = (this.monthlypayment * terminmonths) - this.principal; } 17. The calculate function stores the principal of the loan, computes the monthly payment, and the amount of interest paid. Save and close all the files that make up the custom widget. Part 3: Adding your custom widget to a web page Now you can add your custom Dojo widget to a web page that will be laid out using a Dojo layout widget. You will use Dojo APIs to connect your widget to the output field and display the results. 1. 2. 3. 4. Right-click on the WebContent folder and select New > Web Page. Name the page index.html and click Finish. The wizard created a web page with the necessary code to access Dojo included. At the bottom of the editor click the Design tab to display the page in the Design pane. Open the Dojo Layout Widgets drawer in the palette and drop a BorderContainer onto the page. a. A dialog box pops up allowing you to customize the BorderContainer widget. Click the Top and Center check boxes. - 11 -
b. Click OK. 5. A visual view of the BorderContainer is now displayed in the Design pane. Click on the BorderContainer visualization and then click on the Properties tab. If not selected, click on the BorderContainer tab. 6. 7. Change the height of BorderContainer in the property tab from 500px to 700px. Change the width to 600px. You can also modify the regions (top, center, bottom, etc.) by clicking on the Regions tab. In the top region add the text Loan Payment Calculator. - 12 -
8. Open the Other Dojo Widgets palette drawer and drop the LoanInput widget into the center region of the BorderContainer. 9. Switch back to the Source pane. 10. Add a new div below the LoanInput widget to show the results. You can copy the text from below. <div>monthly Payment: <span id= monthlypayment ></span></div> 11. Rational Application Developer provides content assist templates for commonly used Dojo functions. In the existing script region on your page, below the dojo.require() statements, type dojo.a and invoke content assist. 12. Select the template for dojo.addonload and it will be inserted into your page. 13. Inside the addonload function perform the following steps: a. Type var loanwidget = dijit.b and invoke content assist. Select the byid(id) suggestion so that it inserts into your page. b. Type LoanInput as the parameter for the byid function. c. Type a semicolon after the closing parenthesis for the LoanInput parameter. d. On the line directly below your call to dijit.byid, type dojo.c and invoke content assist. Here you can select another of our default templates for dojo.connect. Insert it into your page. e. Set the first parameter as loanwidget and the second as calculate. f. Inside the function parameter of the connect function add the following code: - 13 -
var payment = loanwidget.monthlypayment if(payment == NaN) { payment = 0; } // update the result field var formattedvalue = dojo.currency.format(payment, {currency: "USD"}); dojo.attr("monthlypayment", "innerhtml", formattedvalue); g. Directly below the existing dojo.require add a new one for: dojo.require("dojo.currency"); h. Your final code for the addonload function should look like the following dojo.addonload(function() { // get the loan input widget var loanwidget = dijit.byid("loaninput"); // connect to the calculate function in the loan input widget // this function will run and update data after every calculation dojo.connect(loanwidget, "calculate", function() { var payment = loanwidget.monthlypayment if(payment == NaN) { payment = 0; } // update the result field var formattedvalue = dojo.currency.format(payment, {currency: "USD"}); dojo.attr("monthlypayment", "innerhtml", formattedvalue); }); }); 14. Save your changes. 15. Now it is time to test your application on the server. Right-click on the index.html file in the Enterprise Explorer and select Run As > Run on Server. 16. Select the Ajax Test Server and click Finish. Your page opens in a web browser. 17. Enter a loan amount and see that the results field updates. - 14 -
Part 4: (Optional) Adding a Pie Chart to your page using the Dojo charting API In this optional section you use content assist and the Dojo charting API to add a pie chart to your results page. The pie chart displays the percentage of total loan costs going towards interest and principle. 1. In the index.html file add the following dojo.require() statements to the existing script tag. dojo.require("dojox.charting.chart2d"); dojo.require("dojox.charting.plot2d.pie"); dojo.require("dojox.charting.action2d.highlight"); dojo.require("dojox.charting.action2d.moveslice"); dojo.require("dojox.charting.action2d.tooltip"); dojo.require("dojox.charting.themes.dollar"); 2. Add the following div directly below the MonthlyPayment div you created to display the result. <div id="chart" style="width: 350px; height: 350px;"></div> 3. Inside the existing addonload function, above the connect function, type var chart = new dojox and invoke content assist. You should see a list of all available Dojo types in the dojox namespace. 4. Continue typing.charting.c and you should see the list begin to filter down. Select dojox.charting.chart2d and insert it on your page. 5. Add the parameter chart, the id for the div node where it will be located on your page. var chart = new dojox.charting.chart2d("chart"); 6. 7. On the next line type chart.set and invoke content assist. You should see the settheme method. Select this method and insert it into the page. As the parameter enter dojox.charting.themes.dollar. chart.settheme(dojox.charting.themes.dollar); 8. Copy the following code on the next line. You can invoke content assist on the various methods and types if you want. This code adds plotting information to your chart and sets up highlighting and tooltips for when users hover over the pie chart slices. You can find more information on Dojo charting APIs here: http://www.dojotoolkit.org/reference-guide/dojox/charting.html#dojox-charting - 15 -
chart.addplot("default", { type: "Pie", labeloffset: -30, font: "Veranda", radius: 90 }); chart.addseries("paymentseries", []); new dojox.charting.action2d.moveslice(chart, "default"); new dojox.charting.action2d.highlight(chart, "default"); new dojox.charting.action2d.tooltip(chart, "default"); 9. Inside the connect function, below the existing code, add the following code: // add the data series to the chart and render chart.updateseries("paymentseries", [ { y: loanwidget.principal, stroke: "black", tooltip: "Principle" }, { y: loanwidget.interestpaid, stroke: "black", tooltip: "Interest" }]); chart.render(); This code adds a new series of data to the chart and renders it each time the user changes an input value. 10. Save the page and run the page on server. - 16 -
Part 5: (Optional) Insert an Enhanced Dojo Grid In this optional section you learn how to add an Enhanced Dojo Grid to your web page. The DataGrid widget creates a table that looks like a spreadsheet. 1. 2. In the Palette, click the Dojo Data Widgets drawer to open it. Drag a DataGrid and drop it directly below the existing divs created in Part 3 or 4 of this tutorial (see image.) The Dojo DataGrid wizard opens. 3. 4. Clear the Generate JavaScript to populate the grid check box. In the Columns section, specify the column heading labels and JavaScript property for each column: a. In the Heading Label field, enter Payment Number b. In the JavaScript Property field, enter paymentnum c. Click Add. - 17 -
5. Repeat the previous steps to add the following Heading Label - JavaScript Property pairs: Heading Label Principal Paid Interest Paid Balance JavaScript Property principal interest balance 6. Click Finish. In the Source pane, you can see that the html markup for the DataGrid is added, with the JavaScript properties populating the field attribute, and the corresponding heading labels as column names. - 18 -
The dojo require statements for the DataGrid and ItemFileReadStore are added automatically. If needed, move them to the top of the script tag with the other dojo.require statements. <script type="text/javascript"> dojo.require("dijit.layout.bordercontainer"); dojo.require("dijit.layout.contentpane"); dojo.require("loan.loaninput"); dojo.require("dojo.currency"); dojo.require("dojox.charting.chart2d"); dojo.require("dojox.charting.plot2d.pie"); dojo.require("dojox.charting.action2d.highlight"); dojo.require("dojox.charting.action2d.moveslice"); dojo.require("dojox.charting.action2d.tooltip"); dojo.require("dojox.charting.themes.dollar"); dojo.require("dojox.grid.datagrid"); dojo.require("dojo.data.itemfilereadstore"); CSS links are also added to the source code of the Web page. 7. 8. Now you can populate data in the data grid using ItemFileWriteStore. Open the LoanInput.js file. Add the following code right below the monthlypayment attribute. amortizationschedule: {}, 9. Add the following code to the calculate() function at the bottom of the function, inside the else statement. - 19 -
//generate the Amortization Data this.generateamortizationschedule(this.principal, interestrate, terminmonths, this.monthlypayment); 10. Add the following function after the calculate() function. generateamortizationschedule: function(principal, interestrate, terminmonths, monthlypayment) { this.amortizationschedule = []; var currentprincipal = principal; for(var i = 0; i < terminmonths; i++) { var paymentdata = {}; paymentdata.paymentnum = i + 1; paymentdata.interest = (currentprincipal * interestrate).tofixed(2); paymentdata.principal = monthlypayment - paymentdata.interest; currentprincipal = currentprincipal - paymentdata.principal; paymentdata.balance = currentprincipal; this.amortizationschedule.push(paymentdata); } } 11. Save and close LoanInput.js and open index.html 12. Add a dojo.require statement for dojo.data.itemfilewritestore dojo.require("dojo.data.itemfilewritestore"); 13. Add the following code at the bottom of the dojo.connect function. Then run the page on server. //create Store with Data var griddata = {}; griddata.items = loanwidget.amortizationschedule; var gridstore = new dojo.data.itemfilewritestore({ identifier:'mortgagedata', label:"mortgagedata", data:griddata}); //set the store on grid var grid = dijit.byid("gridid"); grid.setstore(gridstore); - 20 -
Part 6: (Optional) Creating a Dojo Custom Build This chapter highlights the steps required to create a Dojo custom build. The purpose of a custom Dojo build is to create an efficient version of Dojo, and of your code, that is suitable for deployment. Learn more about the Dojo Build System here: http://www.dojotoolkit.org/reference-guide/build/index.html#build-index The following steps demonstrate creating a Dojo custom build. 1. 2. 3. 4. Right-click the Enterprise Explorer view and select New > Dojo Custom Build. The Dojo Build Tools wizard opens. Accept the default Profile location. Ensure that you complete a full build of the profile before you build individual layers. To complete a full build, clear the Only Build Selected Layers.check box Specify the build scripts and output directories. You can leave the default values set. Click Next to specify advanced options. - 21 -
1. From the CSS Optimization list, select whether to remove comments and line returns. 2. You can specify whether to delete output directories before building, copy test files into the build, or intern widget templates. When you intern a template, the HTML or CSS file is brought into the JavaScript file and assigned to a string. You can also specify other command line arguments. 5. Click Finish. The Custom Build Output window opens displaying details of the build operation. - 22 -
6. You can click OK to close the Custom Build Output window. The Dojo custom build has built the entire Dojo distribution and the Dojo layer files that you selected into the output folder that you specified in the Custom Build wizard. Part 7: (Optional) Using Firebug to debug web applications This chapter highlights using Firebug to debug web applications. 1. Configure the web application to run on Firefox with Firebug. a. Click Window > Web Browser. b. Select Firefox with Firebug from the Web browsers list. 2. Debug the web application. a. You can set JavaScript breakpoints inside script tags of a web page or in JavaScript files. The breakpoints are automatically transferred to Firebug when you debug on server. Conversely, you can also set breakpoints in Firebug and they will be displayed in Page Designer or the JavaScript editor. - 23 -
b. In Enterprise Explorer, right-click index.html and select Debug As > Debug on Server. c. Click Finish. Your web page opens in Firefox. Firebug will be automatically installed if needed. 3. For information on using Firebug to debug JavaScript visit: http://getfirebug.com/wiki/index.php/main_page - 24 -