Slide 1 - Object Partners_ Inc

Document Sample
Slide 1 - Object Partners_ Inc Powered By Docstoc
					Intro to Building Desktop-Style Web UIs

    JavaScript on Grails



                          Torey Lomenda
                          Senior Consultant
                          Object Partners Inc.

                          torey.lomenda@objectpartners.com
                          http://twitter.com/tlomenda
                          http://www.objectpartners.com/weblog
                          Introduction

 Founded 1996, privately held company
 Minneapolis based
   – Branch office in Omaha, NE
 50 employees and growing
 Enterprise IT Consulting
   – Leveraging leading edge and open source technologies
       • Striving for the highest levels of productivity and quality
   – Delivering mission critical applications that are:
       • Performant
       • Scalable
       • Easier to enhance and maintain
 SpringSource partner
   – Using Spring for 5+ years
   – Excited about Grails
                         Agenda

 Introducing Ext JS and Grails UI
   – Exploring in Ten Steps
   – Event-based Applications (DOM Manipulation, Events,
     Ajax)‫‏‬

 Technologies Working Together
   – Grails Platform

 Demo – Hockey Stats Application
   – Side By Side Comparison of Ext JS and GrailsUI/Yahoo! UI


 Development Practices
           A Note on Javascript Libraries

 Rich UI Goodness
    – Dynamically change DOM and CSS based on user interaction

 Utility Libraries
    – Prototype, script.aculo.us
    – sprinkle effects on existing Web 1.0 app

 Mid-Level Libraries (Utilities and Controls)‫‏‬
    – Yahoo! User Interface (YUI)‫‏‬
    – JQuery
    – Nice foundation to build full features Widgets

 Full-Featured (Out-of-the-box Widgets)‫‏‬
    – Ext JS – A Nice UI Component Model
    – GrailsUI - Extending YUI the Grails Way
    – Dojo
        Introducing Ext JS and Grails UI
       Ext JS                                 Grails UI
JavaScript Namespace: Ext            JavaScript Namespace: GRAILSUI
Provides high performance,           A Grails plugin that provides an
customizable “real-world” UI         extensive tag library of rich ajax
widgets                              components based on the Yahoo! UI
                                     (YUI) JavaScript library and a YUI
Well designed, documented and        extension called the Bubbling Library.
extensible component model
                                     It has been designed for ease-of-use as
Uses adapters to work seamlessly     well as configurability.
with other libraries (YUI, JQuery,
Prototype)
                                          Yahoo! UI (YUI)‫‏‬
Open sourced under GPLv3
                                     JavaScript Namespace: YAHOO
Commercial License                   A set of utilities and controls,
$289 per developer                   written in JavaScript, for building
$1159 for 5 developers               richly interactive web applications
                                     using techniques such as DOM
                                     scripting, DHTML and AJAX.

                                     YUI is available under a BSD
                                     license and is free for all uses.
            Exploring in Ten Steps

Step 0: Layout
Step 1: Menus
Step 2: Dynamic Forms
Step 3: Tree Views
Step 4: Accordions and Tabs
Step 5: Data Grids
Step 6: Search Combo Box/AutoComplete
Step 7: Drag & Drop
Step 8: Rich Text Editor
Step 9: Customize Look and Feel
           Highly Interactive Web Apps

 Websites/Web 1.0
   – Informational based
   – Some advanced features such as eCommerce and Content
     Management
   – CRUD style applications


 Web 2.0 Applications
   – Full featured desktop-style interface; intuitive, immediate
     interaction a user experiences
   – Advanced features like workflow and other processes that
     require a high level of user interaction
             Event-Based Applications

 Paradigm Shift to event-based approach
   – Flow of application determined by change of state or user
     interaction (the event).
   – Event is broadcast
   – Listener/Observer acts on the event
 Common Traps
   – Acting on a component or object before it is in a state to
     handle the action. Caused by mixing procedural
     programming with event-based programming.
 Things to Consider
   – Is the DOM ready? Is the DOM Element available?
     [eg: Ext.onReady(), YAHOO.util.Event.onDOMReady()]
   – Is the component/object in a ready state?
   – Timers to wait for conditions (ie: setTimeout, setInterval)‫‏‬
                               Common Trap

 Procedural Programming
 var panel = new Ext.Panel({
 title: “My Panel”,
 items: [{html: “We are Here!”}]});

 panel.render();
 panel.items.get(0).getEl();           getEl() returns undefined.
                                       Tried to get the element
                                       before render completed.
Event Programming
var panel = new Ext.Panel({
title: “My Panel”,
items: [{html: “We are Here!”}]});

panel.on(“render”,
function(thisPanel) {
     thisPanel.items.get(0).getEl();          getEl() returns DOM
});                                           element. Invoked action
panel.render();                               is event-based.
                            DOM Manipulation
             Ext JS                                  YUI
Finding Nodes                             Finding Nodes
var elById = Ext.get(elId)‫‏‬               var elById = YAHOO.util.Dom.get(elId);
var elBySelector =                        var elBySelector =
    Ext.DomQuery.selectNode(                  YAHOO.util.Selector.query('li a');
      'a.mycls[@href*=”myref”]:first');



Manipulating DOM                          Manipulating DOM
Ext.DomHelper                             YAHOO.util.Dom
                                  Ajax Support
           Ext JS                                 YUI
var successFn = function(res) {         var callback = {
};                                          success: function(res) {
var failureFn = function(res) {             },
};                                          failure: function(res) {
                                            }
Ext.Ajax.request({                      }
    url: 'someUrl',
    method: 'GET|POST',                 YAHOO.util.Connect.asyncRequest(
    success: successFn,                     'POST',
    failure: failureFn                  'someUrl',
});                                         callback,
                                            ['param1=blah']);
          Technologies Working Together

 Enabling Web Technologies
   – CSS (Cascading Style Sheets)‫‏‬
   – DOM (Document Object Model)‫‏‬
   – Javascript & Ajax (Async Javascript)

 Grails Platform
   –   Solid Foundation (Groovy, Spring, Hibernate, SiteMesh)‫‏‬
   –   Plugin Architecture (Spring Security, Rich UI, many others)‫‏‬
   –   Modularity: Easy to build custom plugins
   –   RESTful Web Services
                      The Role of CSS
 Look and Feel
   – Visual Styling
   – Positioning
 Cool Effects
   – Examples: Drag & Drop, Expand/Collapse, Overlaying,
     many others




                        CSS Box Model
DEMO: Hockey Stats Manager
               Use Case Model

                            Administer
                             Leagues

League Admin



                          Manage Players

Player Admin




                         Manage Scouting
                            Reports
  Scout
                             Domain Model
                                        Role

          RequestMapping

                                        User




                Team                    Player                ScoutingReport



         home      visitor

                                                              ScoutingNotes
                Game           PlayerStats       PlayerNews



League      Season
            Component Model
                    Hockey Stats App Using Ext JS



                                                   <Grails Plugin>
                      hockeystats-extjs
                                                 hockeystats-domain
          HTML
          (GSP)                                     <Grails Plugin>
                                                        ext-js


                                                                          <Grails Plugin>
                                                                               acegi
           REST
                                                                         (Spring Security
          (JSON)

                                     RESTful Web Sevices
                                    (League, Team, Player,
Browser                                Scouting Report)

                   Hockey Stats App Using Grails UI



                                                      <Grails Plugin>
                        hockeystats-yui
                                                    hockeystats-domain

          HTML
          (GSP)                                     <Grails Plugin>
                                                       Grails UI


                                                    <Grails Plugin>
                                                      Bubbling

                                                                          <Grails Plugin>
          REST                                      <Grails Plugin>            acegi
          (JSON)                                          yui            (Spring Security)
                     Step 1 – Border Layout
          Ext JS                                                 YUI
var viewport = new Ext.ViewPort({            var layout = YAHOO.widget.Layout({
    layout: 'border',                            units: [
    renderTo: 'some-div',                            {position: 'top',
items: [                                                  body: 'header-div'},
     {region: 'north',                               {position: 'left',
          xtype: 'panel'},                                body: 'side-div'},
         {region: 'west',                            {position: 'bottom',
          xtype: 'panel'},                                body: 'footer-div'},
         {region: 'south',                       ]
          xtype: 'panel'},                   });
]
});




                         *Leverage Grails SiteMesh Integration
                             Step 2 – Menus
                Ext JS                        YUI
new Ext.Toolbar({                    var menu =
renderTo: 'some-div',                new YAHOO.widget.Menubar();
items: [
     {text: “Home”,                  menu.addItems([
          xtype: “tbbutton”,         {text: “Home”,
          handler: someFn},               onclick: someFn
         {xtype: “tbseparator”},     },
         {text: “Stats Menu”,        {text: “Stats Menu”
          xtype: “tbbutton”,              submenu: {
               menu: [                      id: “sub1Menu”,
               {title: “Sub 1”,             itemData: [
                  disabled: false;             {text: “Sub 1”,
                  handler: someFn                    disabled: false,
               }                                     onclick: someFn
          ]                                    }
     }                                      ]
]                                    }
});                                  ]);
              Step 3 – Dynamic Forms
        Ext JS                        Grails UI / YUI
Nice Dynamic Forms              Minimal GrailsUI support for
                                Forms
Highlighted Features:
Rich ComboBox Support           Grails UI Widgets:
Collapsible Field Sets          Date Picker
Built-in Field Validation       Expandable Panel
Binding buttons to forms
                                Why the SplitButton?
Can use applyTo() to decorate   Should have used Grails UI
existing HTML form.             Autocomplete

Preferred option is dynamic     YUI decorates existing HTML form
                                markup

                                Custom validation can be added
                                to a form
                           Step 4 - Trees
               Ext JS                        YUI
  Use:                                   Use:
  Ext.tree.TreePanel                     YAHOO.widget.TreeView
  Ext.Tree.TreeLoader                    YAHOO.util.Connect
new Ext.tree.TreePanel({         var loadFn = function(node,
useArrows: true,                                onCompleteCallback) {
                                 // Some Ajax call then complete
root: {                          ...
     nodeType: “async”,          onCompleteCallback();
     text: “Some Tree”,          };
     draggable: false,
     id: “someRootNode”          var tree =
},                               new YAHOO.widget.TreeView(“Tree”);
                                 var root = tree.getRoot();
loader: someTreeLoader           var node = new YAHOO.widget.TextNode({
});                              label: “Some Node”,
                                 labelElId: “someNodeId”}, root);

                                 node.id = “attachIdToNode”;
                                 node.labelElId = “someNodId”);
                                 node.setDynamicLoad(loadFn);
                Step 5 – Accordions & Tabs
              Ext JS                      Grails UI
var p = new Ext.Panel({          <gui:accordion id='someId'
    layout: 'accordion',         class=”someCls”>
    renderTo: 'some-div',        <gui:accordionElement id=”1”
cls: 'someCls',                       title=”Blah”>
items: [                              <div />
     {title: 'Blah'              </gui:accordionElement>
          collapsed: true,       <gui:accordionElement id=”2”
          xtype: 'panel'              title=”Blah”>
     },                               <gui:tabView>
         {title: 'Blah Tabs',              <gui:tab id=”tab1”
          collapsed: true,                      title=”Tab1”>
          xtype: 'panel',                       <div />
          items: [                         </gui:tab>
            xtype: 'tabpanel',        <gui:tabView>
            activeItem: 0,       </gui:accordionElement>
            items: [// tabs]     </gui:accordion>
          ]
     }
]
});
                        Step 6 – Data Grids
              Ext JS                         Grails UI
var someGridStore =              Markup:
new Ext.data.JsonStore({         <gui:dataTable id=“someDataTable”
     data: dataObj,                draggableColumns=“true”
     root: “dataRoot”,             columnDefs=“[
     fields: [                   [key:‘col1’, label:‘Col 1’],
           {name: “col1”},       [key :’col2’, label:’Col 2’]
           {name” “col2”}          ]“
     ]                             sortedBy: “col1”
});                                controller: “someController”
new Ext.GridPanel({                action: “someAction”
store: someGridStore,              params: [id:0]
autoHeight: true,                  resultList: “dataRoot”
columns: [                         rowExpansion: false
     {header: “Col 1”,             rowsPerPage: 10
           dataIndex: “col1”},
       {header: “Col 2”,         />
           dataIndex: “col2”}
],                               JS Code (Refresh Data):
                                 GRAILSUI.someDataTable.
viewConfig: {                      getDataSource().
     forceFit: true,             sendRequest(“id=xxx”, callback);
     getRowClass: someCssFn
}
});
               Step 7 – Custom Search Combo
                 Ext JS                          GrailsUI / YUI
var resultTemplate = Ext.XTemplate(   Markup:
‘<tpl for=“.”>’ +                     <gui:autoComplete
‘<div id=“someItem”{id}’ +            id=“someCombo”
     ‘({name})’ +                     resultName=“dataRoot”
‘</div>’ +                            labelField=“resultLabel”
‘</tpl>’                              idField=“id”
                                      controller=“someController”
new Ext.form.ComboBox({               action=“someAction”
store: someStore,                     minQueryLength=“1”
typeAhead: false,                     typeAhead=“false”
loadingText: “”,                      resultTypeList=“false”
cls: “”,
pageSize: 10,                         JS Code (Refresh Data):
minChars: 1,                          //Attach Behaviour
hideTrigger: true,                    GRAILSUI.someCombo_autocomplete.
tpl: resultTemplate,                    doBeforeParseData =
itemSelector: “div.someItem”               function(req, res, callback) {
});                                              // Build resultLabel
                                            };
                                      GRAILSUI.someCombo_autocomplete.
                                        formatResult = function(d, q, m) {
                                            // Put formatting code here
                                        };
                      Step 8 – Drag & Drop
              Ext JS                       YUI
var dragSource =               var dragSource =
new Ext.dd.DragSource(         new YAHOO.util.DDProxy(
     ‘someDivElementId’,            ‘someDivElementId’);
     {someConfig: “prop1”});
                               dragSource.startDrag = function() {
var dropTarget =               // Do Something
new Ext.dd.DropTarget(         }
     ‘someDropTarget’,
     notifyDrop: someFn});     dragSource.onDragDrop =
                               function(event, id) {
                                    // Use id of node you are
                                    // Dropping into
                               }

                               var dropTarget =
                               new YAHOO.util.DDTarget(
                                    ‘someDropTargetId’);
                Step 9 – Rich Text Editor
            Ext JS                           GrailsUI / YUI
Use 3rd Party Widgets such as     <gui:dialog title=“Some Editor”
TinyMCE                           draggable=“true
(http://tinymce.moxiecode.com/)   modal=“true”
                                  buttons=“[
                                    [text: ‘Ok’, isDefault: true]
                                  ]”
                                  triggers:[]>

                                  <gui:richEditor id=“SomeId”
                                       value=“Default Text” />
                                  </gui:dialog>
                                      Step 10 – Look & Feel
     * Understand the DOM generated. Use Firebug
       to Inspect DOM.
                           Ext JS (Style Accordion)‫‏‬              Grails UI (Style Accordion)‫‏‬
.my-accordion {                                         #playerProfileInfoAccordion .actions {  left:2px;
}                                                       margin-right: 10px;
.my-accordion .x-panel,                                 position:absolute;
.my-accordion .x-accordion-hd {                         text-align:right;
background: none;                                       top:5px;
}                                                       }
.my-accordion .x-panel-body {            border: 0px;   #playerProfileInfoAccordion .yui-panel{ border:
}                                                       0px;
.my-accordion .x-panel-header {          background:    border-style: none !important;
transparent none repeat scroll 0 0;
                                                        }
border-bottom:1px solid !important;                     #playerProfileInfoAccordion .hd { background:none
border-left:medium none;
                                                        !important;
border-right:medium none;     border-top:medium         width: 95%;
none;                                                   border-bottom: 1px solid !important;
width: 95%;                                             border-right: 0px !important;
margin-top: 10px;                                       padding:0 20px !important
}.my-accordion .x-tool {
float: left;
}.my-accordion .x-panel-header-text {
margin-left: 5px;
font-weight: bold;
}
                    General Comparison
            Ext JS                                GrailsUI / YUI
 Pros                                    Pros
   – Powerful, intuitive, easy to use.      – Powerful, intuitive, easy to use.
     (it actually works??)‫‏‬                   (it actually works??)‫‏‬
   – Readable, extensible JS                – Nice tag support to embed
     component model                          components through mark-up
   – feature rich components out-of-        – Active communities
     the-box. Many config options             (SpringSource, Yahoo)‫‏‬
     available.                             – YUI has good documentation
   – Lazy instantiation of                    and samples
     components
                                          Cons
   – Good documentation and
                                            – Not as many features, eye
     samples
                                              candy and customizable options
 Cons                                        as Ext JS
   – Commercial license ($289 per           – Grails UI documentation beyond
     developer, $1159 for 5                   getting started documents
     developers)‫‏‬                           – YUI is a powerful library, but
   – 2.2.x lacks accessibility                needs to be extended with
     standards. 3.0 to change that.           custom code for more flashy
                                              components
              A Note on Performance

 Load time. Loading an application with lots of
  JavaScript and CSS.
   – Optimize with the help of Yslow Profiler

 Memory Footprint and execution speed on the
  Browser
   – JavaScript not known to be a fast language
   – DOM elements take up a lot of memory
   – JavaScript libraries strong focus on performance. Use
     them
   – Research coding optimization techniques. Especially on IE

 Browsers – support for Ajax applications getting
  better
              A Note on Web Accessibility

 Accessibility Guidelines
    – Section 508 of Rehabilitation Act
    – W3C Web Content Accessibility Guidelines (WCAG)

 Accessible Alternatives
    – Degrading gracefully (Grade A browsers to lower grades)‫‏‬
    – Providing an alternate site if Javascript is disabled (Gmail)

 Keyboard Navigation

 Screen Reader friendly generated HTML

 Notify user when Javascript changes appearance

 Both YUI and Ext JS are embracing 508 support.
                   Development Experience

 Groovy/Grails on Eclipse
    – Need custom setup for a tolerable IDE experience. Blog coming soon
 Aptana
    – JavaScript Editor
    – IDE for AJAX Development
 Firebug
    – JS debugging
    – DOM inspection
    – CSS control
    – More...
 YSlow (Performance Recommendations)‫‏‬
    – Performance Report Card based on 13 rules from Yahoo!'s Exception
      Performance team
 Testing Tools
    – Selenium
    – HtmlUnit
    – env.js
    – Screw.Unit
                              References

 Demo code available at
 Recommended Books
    – Ajax in Action. Dave Crane, Eric Pascarello, Darren James
    – JavaScript Ninja. John Resig
    – Ajax Security. Billy Hoffman, Bryan Sullivan

    – Learning Ext JS. Shea Frederick, Colin Ramsay, Steve 'Cutter' Blades
    – Learning Yahoo! User Interface. Dan Wellman
    – Definitive Guide To Grails. Graeme Roche


 Reference Sites
    – Ext JS (www.extjs.com)‫‏‬
    – YUI (http://developer.yahoo.com/yui/)‫‏‬
    – Grails UI (http://www.grails.org/GrailsUI+Plugin)‫‏‬
    – Grails (www.grails.org)‫‏‬
                        Final Word?

 Embrace JavaScript and Ajax technologies
   – They‫‏‬are‫‏‬elegant‫‏‬and‫‏‬are‫“‏‬fun”‫‏‬to‫‏‬work‫‏‬with‫(‏‬once‫‏‬you‫‏‬get‫‏‬
     the hang of it.
 Grails is Grrreat!!
   –   Straight forward for Java developers to pick up
   –   Allows for rapid development
   –   Features via plugins will only continue to grow
   –   SpringSource support means the product will only get better
 Ext JS is a quality product. Is it worth $289?
 Grails UI is promising. Is generating in-line
  JavaScript a problem?

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:6
posted:2/28/2012
language:English
pages:33