Dojo:              Web Application Tools Dylan Schiemann, CEO, SitePen, Inc. pearson://re.mix April 13, 2011© SitePen, Inc...
© SitePen, Inc. All Rights Reserved
Nice to Meet you      Dylan Schiemann                                      Co-Founder of Dojo Toolkit                     ...
I TravelSince January 2009 (mileage is inaccurate, actually > 600,000 miles)© SitePen, Inc. All Rights Reserved
© SitePen, Inc. All Rights Reserved
SitePen: We help our clients build great apps.               Desktop and Mobile Web App Development, Design, Advice       ...
Dojo Toolkit: Project Goals               Fill Web Gaps (browsers, platforms)               Fast & Efficient                ...
http://zetafleet.com/i/4d75a4efc33d4.png© SitePen, Inc. All Rights Reserved
@dojodidit© SitePen, Inc. All Rights Reserved
Dojo 2.0 Vision: Reinventing App Development© SitePen, Inc. All Rights Reserved
Evolution               Web 1.0                      Dumb client, smart server                      Focus on HTML & CSS, "...
Revolution: Separation of Data and UX               You want access to your data, and information                      in ...
Multifarious Experiences© SitePen, Inc. All Rights Reserved
Data Access: Dojo Object Store               Work on HTML5 IndexedDB recommendation                      key/value approac...
Dojo Object Store API               get(id, options) - Gets an object by identity               query(query, options) - Pe...
Simple Example      foodStore = new dojo.store.JsonRest({          target: "/Food/"      });      foodStore.get("cherry")....
Core Stores               Concrete Stores                      Memory - In memory                      JsonRest - Connecte...
Store Wrapper               Takes a store, returns one with added functionality                      Cache, validate, etc....
Comet Notifications with Observable                Observable also adds notify() method                      Call notify()...
JSON Schema + JavaScript               Adds typing/classes to JavaScript                      Unobtrusive                 ...
JSON Schema      schema:      {"description":"A person",        "type":"object",        "properties":         {"name": {"t...
Schemas               DB defined schema: Relational DBs               Schema free: Document DBs               Evolutionary...
Evolutionary Schemas with JSON Schema               Start without a Schema               Add constraints as application ev...
JSON Schema driven UI       Start with schema                           Document interfaces and       Validate JSON/object...
Querying               Web-safe portability important               SQL extremely hard to make secure and too complicated ...
Widgets and Templating© SitePen, Inc. All Rights Reserved
Overview               Dojo and others have Dijits, or templating like DTL or               Mustache               Conveni...
Dijit© SitePen, Inc. All Rights Reserved
What’s a widget                                      Encapsulation of functionality                                      C...
Dijit               Drop-in replacements for the standard HTML web controls.               Leverages existing machinery fr...
Dijit Precepts               CSS, HTML, and JavaScript should be easily separated                      Dijits should act l...
Layout Widgets               Made up of containers and               panes               Dijit Panes fit inside of the    ...
Layout & dijit.layout._LayoutWidget                                        Top                               Top          ...
Dialogs and Tooltips             Modal Dialog             Fixes iframe/Flash/Java/etc             bleed through problem   ...
Form Widgets               Build on top of the very               limited set of built-ins               Can remove constr...
Rich Text Editor      WYSIWYG      Rich text editing      Customizable toolbar with plugins© SitePen, Inc. All Rights Rese...
Dijit Tree                                      Efficient method of accessing                                      large, hi...
DataGrid             Rich feature set and API          Selectable Rows             Acts like a spreadsheet           Colum...
Dojo Charting© SitePen, Inc. All Rights Reserved
Dojo, Dijit, DojoX, and HTML Forms               Forms are an essential component to most websites               Form vali...
Dijit Form Widgets               Button                 RadioButton               CheckBox               Select           ...
Text Boxes and Text Areas                Keeps INPUT element’s checked state                Acts as a base for many other ...
DojoX Enhanced Form Widgets               BusyButton              RadioStack               CheckedMultiSelect      Rating ...
RangeSlider                Two different classes:                HorizontalRangeSlider                and VerticalRangeSlid...
Form Validation with dojox.validate          Contains numerous regular expressions to validate common          input forma...
dojox.validate Example - Programmatic      // Get required classes      dojo.require(dijit.form.ValidationTextBox);      d...
dojox.validate Example - Declarative      <script>        // Get required classes        dojo.require(dijit.form.Validatio...
Form Manager          Provides seamless key-value access to form widgets, DOM          form elements, and attached DOM nod...
dojo.Stateful          Provides new methods for Stateful objects:               get - accesses a stateful object’s named p...
Basic dojo.Stateful Usage      // Create Stateful object      var obj = new dojo.Stateful({          color: red      });  ...
dojo.Stateful and Forms          Can be used with Form Manager or independently          Extremely useful when using XHRs ...
Resource Loading© SitePen, Inc. All Rights Reserved
Overview: Resource Loading               Package Management                      Modularity of code as well as ease of cro...
Modules               First and most important work of CommonJS               Very widely implemented                     ...
Modules Basics               Three "free variables"                      free variable is a variable that is part of the s...
require()               Module IDs                      System modules ("sys", "net")               Relative IDs          ...
require()      greeting.js:      exports.getGreeting = function(){         return “Hello, World”;      };      hello.js:  ...
AMD - Asynchronous Module Definition               CommonJS modules arent optimized for browser use               (possibl...
AMD Formats      // addTen.js      define(["math"], function(math){        return function(x){          return math.add(x,...
AMD - Asynchronous Module Definition               Implementations                      RequireJS, Backdraft, curl.js     ...
Sharing Client and Server Strategies                Transport/wrapping                      transporter                   ...
CommonJS Packages               A set of modules that work together in a package               Specification suggests dire...
dojox.socket© SitePen, Inc. All Rights Reserved
WebSockets               Enables real-time web, or Comet               WebSocket is a technology providing for bi-directio...
Basic WebSocket Sample      // Open the socket      var socket = new WebSocket("ws://localhost:8080/services/infoPusher");...
dojox.socket               Wraps the WebSocket API with an API consistent with the               rest of the Dojo Toolkit ...
dojox.socket Sample    // Create dojox.socket instance    var socket = new dojox.socket("/comet");    // Create open event...
dojox.socket.Reconnect Sample      // Create dojox.socket instance      var socket = new dojox.socket("/comet");      // M...
dojox.socket and Object Stores               dojox.socket instances can notify Object Store when               messages ar...
dojox.socket & Object Stores Sample      // Create Object Store      define("my-module", function(require){          var J...
Force Long-Polling                Not all servers support WebSockets                You can force Long-Polling with dojox....
dojox.socket with Comet      var socket = dojox.socket("/cometd");      function send(data){               return socket.s...
dojox.socket with Comet (cont.)      // Wait for response so we can connect with the provided client id      data = dojo.f...
dojox.socket and Comet Servers               dojox.socket works with CometD, Socket.IO, Tunguska,               Hookbox, O...
3 Dojo Foundation                            Mobile Projects© SitePen, Inc. All Rights Reserved
Wink Toolkit                                      Most Experimental                    Completely separate code     Starte...
EmbedJS                                      Most Complete Core                      Dojo APIs, stripped down   Target eac...
DojoX Mobile                          Mix and Match with Dojo, Rich Set of Components               Started in Dojo 1.5   ...
TweetView and Feature Explorerhttp://dojotoolkit.org/documentation/tutorials/1.6/mobile/tweetview/intro_tweetview/© SitePe...
Result: Modular Tools          Tools to mix and match to                 Modular enough for very          create your app ...
Thanks! Q&A     SitePen sitepen.com     Dojo Toolkit dojotoolkit.org     Twitter: @dylans @sitepen @dojo© SitePen, Inc. Al...
Upcoming SlideShare
Loading in …5
×

Dojo Web Application Tools- April 2011

1,860 views

Published on

Dojo Web Application Tools- eCollege reMix 2011

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,860
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • Introduce self, background, &amp;#x201C;how I got into JavaScript&amp;#x201D; current roles\nGo around room and get intros from students\n
  • Introduce self, background, &amp;#x201C;how I got into JavaScript&amp;#x201D; current roles\nGo around room and get intros from students\n
  • Introduce SitePen; more details are on the next slide.\n
  • SitePen CEO Dylan Schiemann is a Dojo Toolkit co-founder. Many other SitePen employees are core contributors to the Dojo Toolkit and other popular JavaScript projects.\nFOSS = Free Open Source Software\n\n\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Quick whistle-stop tour of widgets\n
  • Clarify the distinction btw. widgets and nodes. Widgets are the puppetmaster, man behind the curtain, (or whatever analogy).\n
  • \n
  • \n
  • Note: Layout Widgets can contain other layout widgets without needing to be nested inside intermediary panes\n
  • Layout widgets implement at least the layout method, \n(possibly by inheriting from _LayoutWidget)\nand pass the call along to any layout-aware children\n
  • \n
  • \n
  • \n
  • Encourage students to explore the dijit folder, docs pages and theme tester\n
  • Explain the required and packaging &amp;#x2013; you may even want to flip over to your file system and show them where the DataGrid.js file is located. \n\n
  • \n
  • Be sure to emphasize not only that Dojo has form widgets and helpers, but WHY they should be used (the sub-bullets in the slide)\n
  • { Big list shown to highlight Dojo having a lot of them &amp;#x2014; we&amp;#x2019;ll hit a few in more detail on subsequent pages }\n
  • \n
  • { Big list shown to highlight Dojo having a lot of them -- we&amp;#x2019;ll hit a few in more detail on subsequent pages }\n
  • A horizontal range slide with a possible value between 50 and 100 with 10 different increments between them.\n
  • \n
  • The &amp;#x201C;emailField&amp;#x201D; widget uses the &amp;#x201C;validator&amp;#x201D; attribute to define a function that validates the field. Same with the &amp;#x201C;urlField&amp;#x201D; widget.\n\nThe &amp;#x201C;urlField2&amp;#x201D; widget uses a expression in the &amp;#x201C;regExp&amp;#x201D; option to validate the input&amp;#x2019;s value against.\n
  • The &amp;#x201C;email&amp;#x201D; element is uses the &amp;#x201C;validator&amp;#x201D; attribute to define a function that validates the field.\n\nThe &amp;#x201C;website&amp;#x201D; element uses an inline regular expression in the &amp;#x201C;regExp&amp;#x201D; attribute to validate the input&amp;#x2019;s value against\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • First example, we list dependencies which match up with arguments passed to the module factory function\nSecond example, we wrap a commonjs module and use the standard CommonJS variables (require, exports)\nThird example we explicitly specify the id of the module. This is used by builds and allows you to include a module as &lt;script&gt; directly in markup.\nFour example, the module is defined directly as an object literal. This is very useful modules that are plain objects and have no dependencies like configuration data.\n
  • \n
  • Transports provide a mechanism for wrapping CommonJS modules so they can be consumed by asynchronous client side module loaders like Dojo and RequireJS. Each of these transport projects uses a little different strategies for wrapping modules, but the goal is to allow a module to be used on the server (in plain CommonJS format) and in the browser (wrapped properly for use in script tags)\n
  • \n
  • \n
  • Protocol Spec here: http://www.whatwg.org/specs/web-socket-protocol/\n
  • \n
  • - Explain LongPolling being a prolonged connection to the server via regular AJAX, dojox.socket designed to allow for maximum flexibility with different protocols while giving back WebSocket-to-long-polling fallback capability\n
  • - Basic example of dojox.socket usage\n
  • - Passes basic socket to dojox.Socket\n
  • \n
  • \n
  • - A basic usage of LongPolling\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Dojo Web Application Tools- April 2011

    1. 1. Dojo: Web Application Tools Dylan Schiemann, CEO, SitePen, Inc. pearson://re.mix April 13, 2011© SitePen, Inc. All Rights Reserved
    2. 2. © SitePen, Inc. All Rights Reserved
    3. 3. Nice to Meet you Dylan Schiemann Co-Founder of Dojo Toolkit CEO, SitePen, Inc. President, Dojo Foundation @dylans @sitepen @dojo© SitePen, Inc. All Rights Reserved
    4. 4. I TravelSince January 2009 (mileage is inaccurate, actually > 600,000 miles)© SitePen, Inc. All Rights Reserved
    5. 5. © SitePen, Inc. All Rights Reserved
    6. 6. SitePen: We help our clients build great apps. Desktop and Mobile Web App Development, Design, Advice Support & Training Strong advocates and contributors of FOSS Works with some amazing companies and organizations:© SitePen, Inc. All Rights Reserved
    7. 7. Dojo Toolkit: Project Goals Fill Web Gaps (browsers, platforms) Fast & Efficient Modular, Small Base, Extensible Professional & Sophisticated Powerful Developer productivity and tools Push the limits (vector graphics, offline, html5, etc.) Open, free, & liberally licensed© SitePen, Inc. All Rights Reserved
    8. 8. http://zetafleet.com/i/4d75a4efc33d4.png© SitePen, Inc. All Rights Reserved
    9. 9. @dojodidit© SitePen, Inc. All Rights Reserved
    10. 10. Dojo 2.0 Vision: Reinventing App Development© SitePen, Inc. All Rights Reserved
    11. 11. Evolution Web 1.0 Dumb client, smart server Focus on HTML & CSS, "separation of markup and presentation" Web 2.0 Smarter client, smart server, conflict Initial break of many paradigms Search indexing, history, navigation Didnt really account for mobile DOM-centric Ajax: sort of real-time© SitePen, Inc. All Rights Reserved
    12. 12. Revolution: Separation of Data and UX You want access to your data, and information in a variety of experiences relevant to your current context Aggregation User Interfaces and experiences Challenging past assumptions statelessness, truly embracing REST abusing markup for "separation of markup and presentation" control and federation of data© SitePen, Inc. All Rights Reserved
    13. 13. Multifarious Experiences© SitePen, Inc. All Rights Reserved
    14. 14. Data Access: Dojo Object Store Work on HTML5 IndexedDB recommendation key/value approach to data access local storage but useful in other contexts accessing data stores (JSON, XML, REST, etc.) matches nicely with NoSQL implemented in Persevere (middleware for SSJS, Node or Narwhal+Jack) very clean approach to getting and setting data modular layering of functionality like notifications© SitePen, Inc. All Rights Reserved
    15. 15. Dojo Object Store API get(id, options) - Gets an object by identity query(query, options) - Performs a query put(object, options) - Stores/updates an object add(object, options) - Adds an object to the store remove(id, options) - Deletes an object getIdentity(object) - Get the identity from an object© SitePen, Inc. All Rights Reserved
    16. 16. Simple Example foodStore = new dojo.store.JsonRest({ target: "/Food/" }); foodStore.get("cherry").then(function(cherry){ cherry.color = "red"; foodStore.put(cherry); }); foodStore.remove("pickle"); foodStore = dojo.store.Observable(foodStore); var query = foodStore.query({color:"red"}); query.forEach(function(food){...}); query.observe(function(object, oldIndex, newIndex){...});© SitePen, Inc. All Rights Reserved
    17. 17. Core Stores Concrete Stores Memory - In memory JsonRest - Connected to store through HTTP/REST DataStore - Adapter for old Dojo Data stores Store Wrappers Observable© SitePen, Inc. All Rights Reserved
    18. 18. Store Wrapper Takes a store, returns one with added functionality Cache, validate, etc. Like middleware for stores© SitePen, Inc. All Rights Reserved
    19. 19. Comet Notifications with Observable Observable also adds notify() method Call notify() to notify of changes from server WebSockets API support socket.on("message", function(event){ store.notify(event.object, event.existingId); });© SitePen, Inc. All Rights Reserved
    20. 20. JSON Schema + JavaScript Adds typing/classes to JavaScript Unobtrusive Flexible Dynamic Portable Easy to integrate with: data/object stores web storage local storage© SitePen, Inc. All Rights Reserved
    21. 21. JSON Schema schema: {"description":"A person", "type":"object", "properties": {"name": {"type":"string"}, "age" : {"type":"integer", "maximum":125}} } instance: {“name”: ”Kris”, “age”: 30}© SitePen, Inc. All Rights Reserved
    22. 22. Schemas DB defined schema: Relational DBs Schema free: Document DBs Evolutionary schema: Persevere, Spring 3.0© SitePen, Inc. All Rights Reserved
    23. 23. Evolutionary Schemas with JSON Schema Start without a Schema Add constraints as application evolves© SitePen, Inc. All Rights Reserved
    24. 24. JSON Schema driven UI Start with schema Document interfaces and Validate JSON/object-style data provide API contracts Enforce data constraints on the Can also be used in SMDs (for client side in JsonRestStore RPC) Generate UI with generic clients© SitePen, Inc. All Rights Reserved
    25. 25. Querying Web-safe portability important SQL extremely hard to make secure and too complicated in the browser RQL JavaScript-style syntax Language agnostic Easy to secure© SitePen, Inc. All Rights Reserved
    26. 26. Widgets and Templating© SitePen, Inc. All Rights Reserved
    27. 27. Overview Dojo and others have Dijits, or templating like DTL or Mustache Convenient way to pull data into encapsulated reusable components Grids, Trees, Charts, Accordions, News Feed Items, etc. Presents better building blocks, but still has a bunch of ugly markup underneath even with HTML5 Open question: could we do this with CSS and JSON only? Perhaps with CSSX© SitePen, Inc. All Rights Reserved
    28. 28. Dijit© SitePen, Inc. All Rights Reserved
    29. 29. What’s a widget Encapsulation of functionality Controller for DOM’s View State management Upgrading markup (progressive enhancement) Markup as configuration and placeholder© SitePen, Inc. All Rights Reserved
    30. 30. Dijit Drop-in replacements for the standard HTML web controls. Leverages existing machinery from Core and Base Conforms to accessibility (a11y) standards in accordance with the ARIA (Accessibility for Rich Internet Applications) Maintains a coherent API so that developers can transfer knowledge across multiple widgets and reuse patterns for solving problems Supports a consistent look and feel with stylesheets which makes widgets easily customizable (Themes and Less) Supports the most common browsers across multiple platforms Creation of widgets in markup is just as easy as with JavaScript (or easier)© SitePen, Inc. All Rights Reserved
    31. 31. Dijit Precepts CSS, HTML, and JavaScript should be easily separated Dijits should act like a bundle of resources A controller object should be associated with the DOM it represents Making connections between DOM and the controller object should be easier Dijits should be easily extended© SitePen, Inc. All Rights Reserved
    32. 32. Layout Widgets Made up of containers and panes Dijit Panes fit inside of the containers Containers add controls for how panes are viewed Excellent for dealing with height-related design issues© SitePen, Inc. All Rights Reserved
    33. 33. Layout & dijit.layout._LayoutWidget Top Top Left Center Right Center Right Left Bottom Bottom “Having Layout” Demonstrating the power of Dijit layout http://dante.dojotoolkit.org/static/xd/layout.html resize() layout()© SitePen, Inc. All Rights Reserved
    34. 34. Dialogs and Tooltips Modal Dialog Fixes iframe/Flash/Java/etc bleed through problem Dialogs can launch dialogs Tooltips can self-size and display where there’s a best fit Great for in-place content detail© SitePen, Inc. All Rights Reserved
    35. 35. Form Widgets Build on top of the very limited set of built-ins Can remove constraints e.g. a list of 1,000,000 items Adds a layer for validation© SitePen, Inc. All Rights Reserved
    36. 36. Rich Text Editor WYSIWYG Rich text editing Customizable toolbar with plugins© SitePen, Inc. All Rights Reserved
    37. 37. Dijit Tree Efficient method of accessing large, hierarchical data sets Powered by the dojo.data API Powerful data stores can create rich interactions© SitePen, Inc. All Rights Reserved
    38. 38. DataGrid Rich feature set and API Selectable Rows Acts like a spreadsheet Column hiding Sortable/Re-orderable columns Requires a Dojo data store© SitePen, Inc. All Rights Reserved
    39. 39. Dojo Charting© SitePen, Inc. All Rights Reserved
    40. 40. Dojo, Dijit, DojoX, and HTML Forms Forms are an essential component to most websites Form validation can be tedious, time-consuming Dojo, Dijit, and DojoX enhance forms by: providing an expansive set of form widgets to make form elements more usable and attractive providing a validation library to allow developers to work more efficiently and avoid writing common validation functions and regular expressions providing a form manager to manage widget life cycle providing a framework by which developers may create their custom widgets© SitePen, Inc. All Rights Reserved
    41. 41. Dijit Form Widgets Button RadioButton CheckBox Select ComboBox Textarea CurrencyTextBox TextBox DateTextBox TimeTextBox DropDownButton FilteringSelect ...and more! MultiSelect NumberSpinner© SitePen, Inc. All Rights Reserved
    42. 42. Text Boxes and Text Areas Keeps INPUT element’s checked state Acts as a base for many other widgets Access widget value via get(‘value’) / set(‘value’) ValidationTextBox allows for basic required=true validation // Get required classes dojo.require(dijit.form.TextBox); dojo.require(dijit.form.ValidationTextBox); dojo.require(dijit.form.Textarea); // Create text box widgets var myTextBox = new dijit.form.TextBox({},myTextBoxId); var myVTextBox = new dijit.form.ValidationTextBox({require:true},myVBoxId); var myTextarea = new dijit.form.Textarea({},myTextareaId);© SitePen, Inc. All Rights Reserved
    43. 43. DojoX Enhanced Form Widgets BusyButton RadioStack CheckedMultiSelect Rating FileInput TimeSpinner FileUploader VerticalRangeSlider HorizontalRangeSlider Manager ..and more! MultiComboBox PasswordValidator© SitePen, Inc. All Rights Reserved
    44. 44. RangeSlider Two different classes: HorizontalRangeSlider and VerticalRangeSlider Allows unrestricted or incremental dragging // Require classes dojo.require(dojox.form.RangeSlider); // Create horizontal range slider var rangeSlider = new dojox.form.HorizontalRangeSlider({ showButtons: false, minimum: 50, maximum: 100, discreteValues: 10 }, myRangeSliderId);© SitePen, Inc. All Rights Reserved
    45. 45. Form Validation with dojox.validate Contains numerous regular expressions to validate common input formats, including: E-mail URL Phone Number Credit Card Validation regular expressions may be locale-specific Highly extendable; add your own validations! Allows you to quickly implement validation; no need to start from scratch. Displays error icon and tooltip for invalid fields© SitePen, Inc. All Rights Reserved
    46. 46. dojox.validate Example - Programmatic // Get required classes dojo.require(dijit.form.ValidationTextBox); dojo.require(dojox.validate.web); // Create ValidationTextBox widget with email address validator var emailField = new dijit.form.ValidationTextBox({ required: true, validator: dojox.validate.isEmailAddress }, emailField); // Create ValidationTextBox widget with url validator var urlField = new dijit.form.ValidationTextBox({ required: true, validator: dojox.validate.isUrl }, urlField); // Create ValidationTextBox widget with regExp validator var urlField2 = new dijit.form.ValidationTextBox({ required: true, regExp: (https?|ftp)://[A-Za-z0-9-_]+.[A-Za-z0-9-_%&?/.=]+ }, urlField2);© SitePen, Inc. All Rights Reserved
    47. 47. dojox.validate Example - Declarative <script> // Get required classes dojo.require(dijit.form.ValidationTextBox); dojo.require(dojox.validate.web); </script> <!-- email validator --> <input type="text" required="true" name="email" id="email" dojoType="dijit.form.ValidationTextBox" validator="dojox.validate.isEmailAddress" /> <!-- inline URL validator --> <input type="text" required="true" name="website" id="website" placeholder="Your Website" dojoType="dijit.form.ValidationTextBox" regExp= "(https?|ftp)://[A-Za-z0-9-_]+.[A-Za-z0-9-_%&?/.=]+">© SitePen, Inc. All Rights Reserved
    48. 48. Form Manager Provides seamless key-value access to form widgets, DOM form elements, and attached DOM nodes Adds custom event handling blocks and observers; this.validate() validates the entire form based on its child element validation setting Observers monitor child elements Avoids the need to keep numerous field variables in a given scope -- simply reference by ID within the Manager instance Requires child widgets to have a “name” property to be grouped into child widgets collection.© SitePen, Inc. All Rights Reserved
    49. 49. dojo.Stateful Provides new methods for Stateful objects: get - accesses a stateful object’s named property set - sets a stateful object’s named property watch - listens to a change in property value unwatch - releases property value change listener watch method is based on Mozilla’s watch function Dijit widgets implement get and set, not watch yet Very useful in organizing and watching object values More information available on the SitePen blog: http://bit.ly/bNqUah© SitePen, Inc. All Rights Reserved
    50. 50. Basic dojo.Stateful Usage // Create Stateful object var obj = new dojo.Stateful({ color: red }); // Watch the label for changes obj.watch(color,function(property,oldValue,newValue) { console.log(The new color is: + newValue); }); // Get the object’s current color var originalColor = label.get(color); // Set the color to something different; watcher is notified obj.set(color,blue); // Unwatch! obj.unwatch(color);© SitePen, Inc. All Rights Reserved
    51. 51. dojo.Stateful and Forms Can be used with Form Manager or independently Extremely useful when using XHRs or likewise technologies to periodically update data that effects form values and calculations. Using dojo.Stateful objects can keep form values and calculations in sync, both ways. Use basic node events on form fields to update Stateful object values and trigger watchers Use Dijit widget events to update Stateful object values and trigger watchers Building block for MVC/MVP with Dojo (dojox.app in Dojo 1.7)© SitePen, Inc. All Rights Reserved
    52. 52. Resource Loading© SitePen, Inc. All Rights Reserved
    53. 53. Overview: Resource Loading Package Management Modularity of code as well as ease of cross-project sharing while reducing side effects and testing complexity Optimization Reduced size balanced with number of requests Feature Detection vs. User-agent optimized builds has.js vs. optimized builds for common user agents CommonJS Modules and AMD© SitePen, Inc. All Rights Reserved
    54. 54. Modules First and most important work of CommonJS Very widely implemented NodeJS (V8) Narwhal (Rhino) RingoJS (Rhino) Yabble (browser) Allows components to declare and use dependencies Allows components to export functionality to other modules© SitePen, Inc. All Rights Reserved
    55. 55. Modules Basics Three "free variables" free variable is a variable that is part of the scope chain above the current module require - Used to load and reference other modules exports - The object that is exported module - Module metadata© SitePen, Inc. All Rights Reserved
    56. 56. require() Module IDs System modules ("sys", "net") Relative IDs resolved relative to current module require(“./sibling”); require(“../parent-sibling”); should be used when possible, improves portability Package/module pattern widely used: require(“some-package/some-module”); Used by NPM, Nodules, RequireJS, Backdraft, others© SitePen, Inc. All Rights Reserved
    57. 57. require() greeting.js: exports.getGreeting = function(){ return “Hello, World”; }; hello.js: var getGreeting = require(“./greeting”).getGreeting; exports.hello = function(){ console.log(getGreeting()); }; require(“./hello”).hello();© SitePen, Inc. All Rights Reserved
    58. 58. AMD - Asynchronous Module Definition CommonJS modules arent optimized for browser use (possible to use them, but non optimal) AMD defines an API to call to register a module Allows modules to execute in a <script> Loader can generate script tags Benefits of script tag based: speed - <script> tags are fast debuggability - real stack traces, named scripts in all debuggers x-domain - No extra work for x-domain, works the same© SitePen, Inc. All Rights Reserved
    59. 59. AMD Formats // addTen.js define(["math"], function(math){ return function(x){ return math.add(x, 10); }); }); // commonjs-style addTen.js define(function(require, exports){ var math = require("math"); exports.addTen = function(x){ return math.add(x, 10); }); }); // Explicit (used by build): define("addTen", ["math"], function(math){ /*...*/}); // Data: define({message: "Hello, World"});© SitePen, Inc. All Rights Reserved
    60. 60. AMD - Asynchronous Module Definition Implementations RequireJS, Backdraft, curl.js New libraries, Dojo 1.6 can run on top of all of them Dojo All Dojo and Dijit modules are in AMD as of 1.6 Works with dojo.require/dojo.provide with default sync loader Nodules Supports plugins “text!template.html” to load HTML/text “i18n!message” to load locale specific data© SitePen, Inc. All Rights Reserved
    61. 61. Sharing Client and Server Strategies Transport/wrapping transporter modulr Flyscript Teleport Nodules or RequireJS to run AMD on server© SitePen, Inc. All Rights Reserved
    62. 62. CommonJS Packages A set of modules that work together in a package Specification suggests directory structure Defines metadata for a set of modules Very widely used in numerous projects Package manager/package registry NPM Dojo Foundation registry for Dojo 1.7 (CPM/CPR)© SitePen, Inc. All Rights Reserved
    63. 63. dojox.socket© SitePen, Inc. All Rights Reserved
    64. 64. WebSockets Enables real-time web, or Comet WebSocket is a technology providing for bi-directional, full- duplex communications channels, over a single TCP socket. Standardized by the W3C: http://dev.w3.org/html5/websockets/ Uses the ws (unsecure) or wss (secure) protocol Provides open, close, error, and message events Provides send and close methods Browser support will emerge in 2011 once secured© SitePen, Inc. All Rights Reserved
    65. 65. Basic WebSocket Sample // Open the socket var socket = new WebSocket("ws://localhost:8080/services/infoPusher"); // Create open event listener socket.onopen = function(e){ console.log("Socket opened successfully!"); } // Create message event listener socket.onmessage = function(event) { console.log("Message received!", event.data); } // Create close event listener socket.onclose = function(e){ console.log("Socket closed!"); } // Create error event listener socket.onerror = function(e){ console.log("Ooops! Error!",e); } // Send a message to the server socket.send("This is my message!"); // Close the socket socket.close();© SitePen, Inc. All Rights Reserved
    66. 66. dojox.socket Wraps the WebSocket API with an API consistent with the rest of the Dojo Toolkit Provides fallback for servers that don’t support WebSockets: dojox.socket.LongPoll Provides dojox.socket.Reconnect to automatically reconnect if disconnected Provides an on method which aliases socket.connect© SitePen, Inc. All Rights Reserved
    67. 67. dojox.socket Sample // Create dojox.socket instance var socket = new dojox.socket("/comet"); // Create open event listener socket.on("open",function(event){ console.log("Socket opened successfully!"); }); // Create message event listener socket.on("message",function(event){ console.log("Message received!", event, event.data); // Send a message back! socket.send("Received your message!"); }); // Customized headers var socket2 = new dojox.socket({ url: "/comet", headers: { "Accept": "application/json", "Content-Type": "application/json" } });© SitePen, Inc. All Rights Reserved
    68. 68. dojox.socket.Reconnect Sample // Create dojox.socket instance var socket = new dojox.socket("/comet"); // Make the socket reconnect if necessary socket = dojox.socket.Reconnect(socket);© SitePen, Inc. All Rights Reserved
    69. 69. dojox.socket and Object Stores dojox.socket instances can notify Object Store when messages are received Observable store (on the server side) provides notification events that work very well with Comet driven updates. Notify the store of changes from the server by calling the notify method on the store Signal a new object by calling store.notify() and omitting the id, and a deleted object by omitting the object A changed/updated object should include both.© SitePen, Inc. All Rights Reserved
    70. 70. dojox.socket & Object Stores Sample // Create Object Store define("my-module", function(require){ var JsonRest = require("dojo/store/JsonRest"); var Observable = require("dojo/store/Observable"); var store = new JsonRest({data:myData}); store = Observable(store); }); // Inform store of message received socket.on("message", function(event){ var existingId = event.data.id; var object = event.data.object; store.notify(object, existingId); });© SitePen, Inc. All Rights Reserved
    71. 71. Force Long-Polling Not all servers support WebSockets You can force Long-Polling with dojox.socket.LongPoll var socket = dojox.socket.LongPoll({ url: "/comet", headers: { "Accept": "application/json", "Content-Type": "application/json", "Client-Id": Math.random() } });© SitePen, Inc. All Rights Reserved
    72. 72. dojox.socket with Comet var socket = dojox.socket("/cometd"); function send(data){ return socket.send(dojo.toJson(data)); } socket.on("connect", function(){ // Send a handshake send([ { "channel": "/meta/handshake", "version": "1.0", "minimumVeresion": "1.0beta", "supportedConnectionTypes": ["long-polling"] } ]).then(function(data){ // response handled on next slide }); });© SitePen, Inc. All Rights Reserved
    73. 73. dojox.socket with Comet (cont.) // Wait for response so we can connect with the provided client id data = dojo.fromJson(data); if(data.error){ throw new Error(error); } // Get the client id for all future messages clientId = data.clientId; // Send a connect message send([ { "channel": "/meta/connect", "clientId": clientId, "connectionType": "long-polling" }, { // also send a subscription message "channel": "/meta/subscribe", "clientId": clientId, "subscription": "/foo/**" } ]); socket.on("message", function(){ // Handle all messages from the server });© SitePen, Inc. All Rights Reserved
    74. 74. dojox.socket and Comet Servers dojox.socket works with CometD, Socket.IO, Tunguska, Hookbox, Orbited, etc. More information about specific Comet servers at the SitePen blog: http://www.sitepen.com/blog/2010/10/31/dojo-websocket/© SitePen, Inc. All Rights Reserved
    75. 75. 3 Dojo Foundation Mobile Projects© SitePen, Inc. All Rights Reserved
    76. 76. Wink Toolkit Most Experimental Completely separate code Started by Orange Labs base iPhone and Android apps, Innovative UI elements (3D consistent look and feel, useful for tight screen other platforms coming space© SitePen, Inc. All Rights Reserved http://winktoolkit.org/
    77. 77. EmbedJS Most Complete Core Dojo APIs, stripped down Target each platform with for mobile and its native look & feel embedded TouchScroll, geolocation, Started by Uxebu etc.© SitePen, Inc. All Rights Reserved http://github.com/uxebu/embedjs/
    78. 78. DojoX Mobile Mix and Match with Dojo, Rich Set of Components Started in Dojo 1.5 Simple mobile UI paradigms, Support for many HTML5 same data interactions features and beyond Native or general themes Grids, charts, maps, gauges© SitePen, Inc. All Rights Reserved
    79. 79. TweetView and Feature Explorerhttp://dojotoolkit.org/documentation/tutorials/1.6/mobile/tweetview/intro_tweetview/© SitePen, Inc. All Rights Reserved
    80. 80. Result: Modular Tools Tools to mix and match to Modular enough for very create your app simple projects, flexible and Separate data from UI logic consistent enough to handle simple and seamlessly the most challenging, feature- rich web apps© SitePen, Inc. All Rights Reserved
    81. 81. Thanks! Q&A SitePen sitepen.com Dojo Toolkit dojotoolkit.org Twitter: @dylans @sitepen @dojo© SitePen, Inc. All Rights Reserved

    ×