SlideShare uma empresa Scribd logo
1 de 37
Dojo for Programmers
Finest tools for programmers by programmers.
About me

• I am Eugene Lazutkin (read: la-ZOOT-kin).
• Started to work with JavaScript since ~1998.
• Worked with Dojo Toolkit since 2005.
• Dojo Committer responsible for core
 improvements, DnD, graphics, and charting.



                       2
This talk is about...

• Programmer's tools of trade.
• Different programming paradigms...
  • ...in JavaScript
     • ...and how Dojo supports them.
• Why do we need them.

                       3
This talk is not about...


• Widgets, maps, charts, grids.
• Browsers, DOM, CSS.
• HTTP, XML, JSON.



                       4
JS before ~2005


• Progressive enhancements:
  • Project code base is small.
  • General complexity is low.
  • No need to structure the code.


                       5
JS now

• Web applications are on the rise:
  • 100s kbytes of minified code.
  • Asynchronous exchange of data with servers.
  • Teams of developers.
  • Reusable components.
  • Modularity.
                       6
Code structure

• Tried and true techniques:
  • Modules
  • OOP
  • AOP
  • EDP
  • FP
                       7
Modules

• Separation of concerns.
• Well-defined API improves maintainability.
• For reusable components: a distribution unit.
• Browsers: a loading unit.
  • Usually roughly corresponds to <script>.

                        8
Modules in Dojo I

• One module - one file.
• Can load other modules.
• Just two functions are visible:
  • dojo.provide() - declare a name of the
    module.

  • dojo.require() - request other module. 

                        9
Modules in Dojo II

• There is no restriction on content of a module.
 Anything goes.

• Usually module defines discoverable names by
 attaching them to well-known global names.

  • Dojo defines "dojo" as a global namespace.
  • General convention is to define your own
    namespaces.

                       10
Modules in Dojo III

• Module names all follow a simple convention:
  • "dojox.gfx.svg" => "dojox/gfx/svg.js".
• Top name can be mapped.
  • The default mapping:
    • "myapp.foo" => "dojo/../myapp/foo.js"
  • Custom mapping can be defined too.
                        11
Modules in Dojo IV

• Your custom modules are first class citizens.
• The default mapping takes care of a common
 case when your subdirectory is a peer of "dojo":

  • /dojo
  • /myapp
• Custom mapping takes care of specific
 requirements of your deployment.

                       12
Example

dojo.provide("dojox.charting.Theme");


dojo.require("dojox.color");
dojo.require("dojox.color.Palette");
dojo.require("dojox.lang.utils");
dojo.require("dojox.gfx.gradutils");


dojo.declare("dojox.charting.Theme", null, {
 // summary:
 //   A Theme is a pre-defined object, primarily JSON-based,
 //   style a chart.



                               13
Why?

• We don't need to track dependencies manually.
  • No need to include dependencies manually.
• We can use the same modules in different
 environments.

  • Dojo is used with Rhino, Spidermonkey,
    Node.js...

• We can automatically optimize our application.
                      14
Dojo tools I


• In browser Dojo comes with two loaders:
  • Simple synchronous XHR-based loader for
    debugging.

  • Cross-domain asynchronous loader for
    CDNs.



                      15
Dojo tools II
• Dojo Builder is used to prep an app for
 deployment.

  • Collecting all required modules in one or
    more layer files.

  • Minification of layers.
  • Collecting and minifying CSS files.
  • Inlining external resources (e.g., HTML
    snippets) in JS.
                       16
OOP

• Proven technique to tame the complexity.
• Modularity on a different level.
• Objects are chunks of state with a well-defined
 compact API.

• Possibility to reuse common behaviors using
 inheritance.


                       17
OOP in JS

• Everything is an object.
• Prototypal inheritance.
• Constructors.
• Dynamic nature:
  • Duck typing - satisfying APIs dynamically.

                       18
OOP in Dojo


• Dojo doesn't try to make JS the language
 "better".

• Dojo doesn't go against the grain.
• Dojo provides helpers for existing patterns.



                       19
OOP the JS way

• Constructor + delegation:
 var MyCtor = function () {
      // construct an object
      this.name = “circle”;
 };


 MyCtor.prototype = {
      // delegate all undefined properties to this object
      radius: 1,
      area: function() { return Math.PI * this.radius * this.radius; }
 };


                                    20
Delegation I
• Common idiom:
 function Temp () {} // does nothing


 dojo.delegate = function (obj, props) {
      Temp.prototype = obj;
      var t = new Temp();
      Temp.prototype = null;
      if (props) {
          dojo.mixin(t, props);
      }
      return t;
 };

                                  21
Delegation II

• dojo.delegate() is one of the oldest functions
 in Dojo.

• This pattern is so common that it was
 enshrined in JS5 as Object.create().

• Still as you can see the constructor function is
 unused.


                        22
Modern OOP techniques

• Problems with classic OOP:
  • Single inheritance is no good at code reuse.
     • A fish, a duck, a hippo, and a submarine
      can swim. Does it mean they have a
      common ancestor?

• Modern approaches: mixins, traits, aspects,
 delegates.

                       23
Mixins I

• Assemble objects from independent "bricks",
  which encapsulate a state and a functionality.

• Each mixin is like a mini-object, yet it doesn't
  make sense on its own.

• It can be composed of other mixins.
• It is (re)used in different objects => all
  dependencies should be anonymous.

                         24
Mixins II

• It can reuse and update existing object
  variables and methods.

• It can have its own state and methods.
• It can be composed of other mixins.
• It participates in a lifecycle.


                          25
Object's lifecycle

• Constructing an object.
• Destructing an object.
  • Required if object uses external resources.
• Application-specific events:
  • Dijit defines events before and after building
    DOM for a widget.


                       26
Interaction with mixin I

• Mixin can use host object's variables and
 methods.

  • The simplest way is to use a convention.
     • Mixin knows names it uses.
     • Object provides proper semantic units
       using those names.


                       27
Interaction with mixin II
• Mixin can refer to object's methods
 anonymously.

  • There is a way to specify how certain
    methods are called:

     • Automatically before/after its host's
      method.

     • Replacing a host's method and using some
      means (a super call) to call host.

                       28
dojo.declare() I
• Simple object + single inheritance:
 // no parent, inherits from Object
 var A = dojo.declare(null, {});
 var a = new A();


 // single inheritance
 var B = dojo.declare(A, {});
 var b = new B();


 a instanceof A; // true
 b instanceof A; // true
 b instanceof B; // true

                                   29
dojo.declare() II

• Mixins:
 var Duck = dojo.declare([Bird, Swimmer], {
      constructor: function (name) {
           this.name = name;
      },
      say: function () { return “Quack!”; }
    });
 var duck_1 = new Duck(“Donald”);
 var duck_2 = new Duck(“Daisy”);
 var duck_3 = new Duck(“Daffy”);



                                30
dojo.declare() III
• Conventions:
  • All mixins and base classes are sorted
    according to C3 MRO (topological sort used
    by Dylan, Perl, Python).

    • All dups are eliminated.
    • Order of dependencies is satisfied.
  • Native prototypal inheritance is used to
    chain all bases and mixins.
                       31
dojo.declare() IV
• Conventions:
  • Constructors are called in reversed order.
    • The deepest one is called first.
  • A super call: this.inherited()
    • No need to know who is "next in chain".
  • Automatic after/before chaining can be
    specified for methods.

                        32
dojo.declare() V


• In general dojo.declare() operates in terms of
 dojo.delegate().

• It automates a frequently occurring pattern
 using simple conventions.

• The only non-trivial addition is a super call.


                        33
How to reach me


• My web site: http://lazutkin.com
• Twitter: http://twitter.com/uhop
• Email: eugene@dojotoolkit.org
• Slides: http://www.slideshare.net/elazutkin


                       34
But wait! There is more!

• Dojo offers much more:
  • AOP tools:
    • Discussed in http://lzt.me/dBc
    • Pete Higgins will talk more about it today.
  • FP tools:
    • Discussed in http://lzt.me/dB6
                      35
And even more!
• Even more tools:
  • EDP:
    • dojo.Deferred is included in the Base to
      handle asynchronous events.

    • dojox.lang.async provides high-level
      primitives to combine/synchronize events:
      seq(), par(), any(), select(), ifThen(),
      loop().

                     36
That’s all for now!




         37

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

iPhone Memory Management
iPhone Memory ManagementiPhone Memory Management
iPhone Memory Management
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Prototype
PrototypePrototype
Prototype
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
Bab5 bluej
Bab5 bluejBab5 bluej
Bab5 bluej
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
1 - OOP
1 - OOP1 - OOP
1 - OOP
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Why Extension Programmers Should Stop Worrying About Parsing and Start Thinki...
Why Extension Programmers Should Stop Worrying About Parsing and Start Thinki...Why Extension Programmers Should Stop Worrying About Parsing and Start Thinki...
Why Extension Programmers Should Stop Worrying About Parsing and Start Thinki...
 
Fields, entities, lists, oh my!
Fields, entities, lists, oh my!Fields, entities, lists, oh my!
Fields, entities, lists, oh my!
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
 
Chapter08
Chapter08Chapter08
Chapter08
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 

Semelhante a Dojo for programmers (TXJS 2010)

GR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL SupportGR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL Support
GR8Conf
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
rsebbe
 

Semelhante a Dojo for programmers (TXJS 2010) (20)

Pulsar
PulsarPulsar
Pulsar
 
The Dojo Toolkit An Introduction
The Dojo Toolkit   An IntroductionThe Dojo Toolkit   An Introduction
The Dojo Toolkit An Introduction
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Ios development
Ios developmentIos development
Ios development
 
GR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL SupportGR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL Support
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
Eusecwest
EusecwestEusecwest
Eusecwest
 
Dojo training
Dojo trainingDojo training
Dojo training
 
.Net introduction
.Net introduction.Net introduction
.Net introduction
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
MongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overviewMongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overview
 
what is .net
what is .netwhat is .net
what is .net
 
On the Edge Systems Administration with Golang
On the Edge Systems Administration with GolangOn the Edge Systems Administration with Golang
On the Edge Systems Administration with Golang
 
DL4J at Workday Meetup
DL4J at Workday MeetupDL4J at Workday Meetup
DL4J at Workday Meetup
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 

Mais de Eugene Lazutkin

Mais de Eugene Lazutkin (16)

Service workers
Service workersService workers
Service workers
 
Advanced I/O in browser
Advanced I/O in browserAdvanced I/O in browser
Advanced I/O in browser
 
Streams
StreamsStreams
Streams
 
Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScript
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.js
 
TXJS 2013 in 10 minutes
TXJS 2013 in 10 minutesTXJS 2013 in 10 minutes
TXJS 2013 in 10 minutes
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
 
OOP in JS
OOP in JSOOP in JS
OOP in JS
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJS
 
RAD CRUD
RAD CRUDRAD CRUD
RAD CRUD
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real world
 
Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Dojo for programmers (TXJS 2010)

  • 1. Dojo for Programmers Finest tools for programmers by programmers.
  • 2. About me • I am Eugene Lazutkin (read: la-ZOOT-kin). • Started to work with JavaScript since ~1998. • Worked with Dojo Toolkit since 2005. • Dojo Committer responsible for core improvements, DnD, graphics, and charting. 2
  • 3. This talk is about... • Programmer's tools of trade. • Different programming paradigms... • ...in JavaScript • ...and how Dojo supports them. • Why do we need them. 3
  • 4. This talk is not about... • Widgets, maps, charts, grids. • Browsers, DOM, CSS. • HTTP, XML, JSON. 4
  • 5. JS before ~2005 • Progressive enhancements: • Project code base is small. • General complexity is low. • No need to structure the code. 5
  • 6. JS now • Web applications are on the rise: • 100s kbytes of minified code. • Asynchronous exchange of data with servers. • Teams of developers. • Reusable components. • Modularity. 6
  • 7. Code structure • Tried and true techniques: • Modules • OOP • AOP • EDP • FP 7
  • 8. Modules • Separation of concerns. • Well-defined API improves maintainability. • For reusable components: a distribution unit. • Browsers: a loading unit. • Usually roughly corresponds to <script>. 8
  • 9. Modules in Dojo I • One module - one file. • Can load other modules. • Just two functions are visible: • dojo.provide() - declare a name of the module. • dojo.require() - request other module.  9
  • 10. Modules in Dojo II • There is no restriction on content of a module. Anything goes. • Usually module defines discoverable names by attaching them to well-known global names. • Dojo defines "dojo" as a global namespace. • General convention is to define your own namespaces. 10
  • 11. Modules in Dojo III • Module names all follow a simple convention: • "dojox.gfx.svg" => "dojox/gfx/svg.js". • Top name can be mapped. • The default mapping: • "myapp.foo" => "dojo/../myapp/foo.js" • Custom mapping can be defined too. 11
  • 12. Modules in Dojo IV • Your custom modules are first class citizens. • The default mapping takes care of a common case when your subdirectory is a peer of "dojo": • /dojo • /myapp • Custom mapping takes care of specific requirements of your deployment. 12
  • 14. Why? • We don't need to track dependencies manually. • No need to include dependencies manually. • We can use the same modules in different environments. • Dojo is used with Rhino, Spidermonkey, Node.js... • We can automatically optimize our application. 14
  • 15. Dojo tools I • In browser Dojo comes with two loaders: • Simple synchronous XHR-based loader for debugging. • Cross-domain asynchronous loader for CDNs. 15
  • 16. Dojo tools II • Dojo Builder is used to prep an app for deployment. • Collecting all required modules in one or more layer files. • Minification of layers. • Collecting and minifying CSS files. • Inlining external resources (e.g., HTML snippets) in JS. 16
  • 17. OOP • Proven technique to tame the complexity. • Modularity on a different level. • Objects are chunks of state with a well-defined compact API. • Possibility to reuse common behaviors using inheritance. 17
  • 18. OOP in JS • Everything is an object. • Prototypal inheritance. • Constructors. • Dynamic nature: • Duck typing - satisfying APIs dynamically. 18
  • 19. OOP in Dojo • Dojo doesn't try to make JS the language "better". • Dojo doesn't go against the grain. • Dojo provides helpers for existing patterns. 19
  • 20. OOP the JS way • Constructor + delegation: var MyCtor = function () { // construct an object this.name = “circle”; }; MyCtor.prototype = { // delegate all undefined properties to this object radius: 1, area: function() { return Math.PI * this.radius * this.radius; } }; 20
  • 21. Delegation I • Common idiom: function Temp () {} // does nothing dojo.delegate = function (obj, props) { Temp.prototype = obj; var t = new Temp(); Temp.prototype = null; if (props) { dojo.mixin(t, props); } return t; }; 21
  • 22. Delegation II • dojo.delegate() is one of the oldest functions in Dojo. • This pattern is so common that it was enshrined in JS5 as Object.create(). • Still as you can see the constructor function is unused. 22
  • 23. Modern OOP techniques • Problems with classic OOP: • Single inheritance is no good at code reuse. • A fish, a duck, a hippo, and a submarine can swim. Does it mean they have a common ancestor? • Modern approaches: mixins, traits, aspects, delegates. 23
  • 24. Mixins I • Assemble objects from independent "bricks", which encapsulate a state and a functionality. • Each mixin is like a mini-object, yet it doesn't make sense on its own. • It can be composed of other mixins. • It is (re)used in different objects => all dependencies should be anonymous. 24
  • 25. Mixins II • It can reuse and update existing object variables and methods. • It can have its own state and methods. • It can be composed of other mixins. • It participates in a lifecycle. 25
  • 26. Object's lifecycle • Constructing an object. • Destructing an object. • Required if object uses external resources. • Application-specific events: • Dijit defines events before and after building DOM for a widget. 26
  • 27. Interaction with mixin I • Mixin can use host object's variables and methods. • The simplest way is to use a convention. • Mixin knows names it uses. • Object provides proper semantic units using those names. 27
  • 28. Interaction with mixin II • Mixin can refer to object's methods anonymously. • There is a way to specify how certain methods are called: • Automatically before/after its host's method. • Replacing a host's method and using some means (a super call) to call host. 28
  • 29. dojo.declare() I • Simple object + single inheritance: // no parent, inherits from Object var A = dojo.declare(null, {}); var a = new A(); // single inheritance var B = dojo.declare(A, {}); var b = new B(); a instanceof A; // true b instanceof A; // true b instanceof B; // true 29
  • 30. dojo.declare() II • Mixins: var Duck = dojo.declare([Bird, Swimmer], { constructor: function (name) { this.name = name; }, say: function () { return “Quack!”; } }); var duck_1 = new Duck(“Donald”); var duck_2 = new Duck(“Daisy”); var duck_3 = new Duck(“Daffy”); 30
  • 31. dojo.declare() III • Conventions: • All mixins and base classes are sorted according to C3 MRO (topological sort used by Dylan, Perl, Python). • All dups are eliminated. • Order of dependencies is satisfied. • Native prototypal inheritance is used to chain all bases and mixins. 31
  • 32. dojo.declare() IV • Conventions: • Constructors are called in reversed order. • The deepest one is called first. • A super call: this.inherited() • No need to know who is "next in chain". • Automatic after/before chaining can be specified for methods. 32
  • 33. dojo.declare() V • In general dojo.declare() operates in terms of dojo.delegate(). • It automates a frequently occurring pattern using simple conventions. • The only non-trivial addition is a super call. 33
  • 34. How to reach me • My web site: http://lazutkin.com • Twitter: http://twitter.com/uhop • Email: eugene@dojotoolkit.org • Slides: http://www.slideshare.net/elazutkin 34
  • 35. But wait! There is more! • Dojo offers much more: • AOP tools: • Discussed in http://lzt.me/dBc • Pete Higgins will talk more about it today. • FP tools: • Discussed in http://lzt.me/dB6 35
  • 36. And even more! • Even more tools: • EDP: • dojo.Deferred is included in the Base to handle asynchronous events. • dojox.lang.async provides high-level primitives to combine/synchronize events: seq(), par(), any(), select(), ifThen(), loop(). 36
  • 37. That’s all for now! 37

Notas do Editor