Your SlideShare is downloading. ×
0
MODERN
JAVASCRIPT
APPLICATIONS
Volodymyr VoityshynRivne 2013
How to get
well structured JavaScript code?
How to get
well structured JavaScript code?
Client JavaScript Evolution
1. Client JavaScript resolved auxiliary
tasks
2. Single Page Web Applications
3. Real time app...
Contents
I. Some Useful Constructions
II. What is wrong?
III. JavaScript & OOP
IV. Module Pattern
V. Object Oriented Desig...
I. Some Useful Constructions
Closures
7
IIFE
8
Named Parameters
Must be
documented
9
It’s useful for
4 and more
parameters
II. What is wrong?
Global Functions
 Avoid global functions
 Use instead:
 Classes
 Modules
11
Mixing JavaScript with HTML
▪ Place HTML and JavaScript in separated files
▪ Assign event handlers with JavaScript
12
Mixing JS & Server Code is Bad
ASP.NET MVC Razor
13
Mixing JS & Server Code is Acceptable
ASP.NET MVC Razor
14
III. JavaScript & OOP
Fact #1
Everything is an object
16
… even primitives and functions
17
Creating an Object
18
Fact # 2
Object members
can be added/deleted dynamically
19
Defining Members
20
Creating an Object with JSON Notation
21
Deleting Members
22
Fact #3
All object members are public
23
Fact #4
Objects are hash tables
24
Access to a Property with []
25
Fact #5
Inheritance is based on prototypes
26
Inheritance
Object
vehicle
+ name
+ run()
bicycle
+ wheels
Sample_2_01
27
Fact #6
Functions can be considered as classes
28
Pseudo Class
Object
Vehicle
+ name
+ run()
29
The “prototype” Property
Object
Vehicle
+ name
+ run()
30
Pseudo Class Inheritance
Object
Vehicle
+ name
+ run()
Bicycle
+ wheels
Sample_2_02
31
Inheritance: Practice Hints
 Avoid a too long prototype chain
 Avoid extending prototypes of built-in objects
 Use fram...
Virtual Functions
33
Static Members
34
IV. Module Pattern
Module Pattern Intent
Provides both private and public
encapsulation for classes
Module Example
▪ Closure is used
for private state
▪ “Public” object is
returned
▪ Created by IIFE
Sample_3_01_Module_Coun...
Import Dependencies
38
Extending
Sample_3_02_Module_Strings
39
Extending jQuery Module
40
Extending Underscore Module
41
Page Code Behind as Module
Page
(HTML + CSS)
Code Behind
(JavaScript
Module)
Handle Events
Read Data
Put Data
42
Sample_3_...
Advantages vs. Disadvantages
 Advantages
 Simple in development
 Possibility of using a page base class
 Disadvantages...
Class as Module
44
V. Object Oriented Design Patterns
V.1. Creational Patterns
“… help make a system independent of
how its objects are
created, composed, and represented”
(GoF)
Factory Pattern Intent
Provides an interface for creating families of
related or dependent objects without specifying
thei...
Classical Abstract Factory
AbstractComponentFactory
- components
+ create(string)
ChComponentFactory IEComponentFactory
Ca...
Service Locator & IoC
 Provides abstract interface for instantiating objects
 Resolves dependencies among objects
 Mana...
Prototype Pattern Intent
Specify the kinds of objects to create using a
prototypical instance, and create
new objects by c...
Prototype by Native JavaScript
Object
p
id, name
p1 p2
Prototype as a Shallow Copy
Object
p3
id, name
p4
id, name
p5
id, name
Prototype as a Deep Copy
Object
p6
id, name
p7
id, name
Classical Prototype
Cloning DOM Elements
V.2. Structural Patterns
“… are concerned with how classes and objects are
composed to form larger structures”
(GoF)
Adapter Pattern Intent
Convert the interface of a class into another
interface clients expect
(GoF)
Client
Expected Interf...
Adapting to Underscore Interface
Decorator Pattern Intent
Attach additional responsibilities to an object
dynamically
(GoF)
Decorator 2
Decorator 1
an Obje...
Classical Decorator
Decorator and IIFE
Decorator with Closure
Façade Pattern Intent
Provide a unified interface to a set of interfaces in a
subsystem. Facade defines a higher-level int...
Façade in jQuery
XMLHttpRequest
$.ajax()
Client
document.createElement()
$(“<tag>”)
Client
Façade: Important Consideration
Performance
Comfortable
Interface
V.3. Behavioral Patterns
“… are concerned with algorithms and the
assignment of responsibilities among objects”
(GoF)
Observer Pattern Intent
Define a one-to-many dependency between objects so that
when one object changes state, all its dep...
Publish/Subscribe
Publish/Subscribe & Backbone Event
Mediator Pattern Intent
Define an object that encapsulates how a set of objects
interact. Mediator promotes loose coupling...
Mediator as Event Buss
Event Buss
Module 1 Module 2
Publishes an event Listens an event
http://thejacklawson.com/Mediator....
Mediator as Web Modules Manager
Web Module 1 Web Module 2
Web Modules Manager
Nicholas Zakas: Scalable JavaScript Applicat...
Strategy Pattern Intent
Define a family of algorithms, encapsulate each one,
and make them interchangeable.
(GoF)
Sorting Algorithms as Strategy
VI. MV* Patterns via BackboneJS
Model – View – Controller
View
Model Controller
Main goal - separate view and data
Top JavaScript MVC Frameworks
Knockout.js
Ember.js
Angular.js
Backbone.js
Backbone Object Types
78
 Events
 Model
 Collection
 View
 Router
Backbone.js Typical Stack
Backbone.js
Underscore.js
jQuery Require.js
Backbone Advantages
80
 Simple in usage
 Defines major types of an application objects
 Gets much freedom for applicati...
VII. Dependencies Management
What is a bad design?
 Inflexibility
 Fragility
 Solidity
Coupling
A measure of how much a module
relies on other modules
Cohesion
A measure of how closely related the members of a
module are to the other members of the same module
HighLow
What is a good design?
 Flexible
 Robust
 Reusable
What’s a main problem?
What is a key to success?
Manage dependencies!
Dependency Inversion Principle
A. High level modules should not depend upon
low level modules. Both should depend upon
abs...
Dependency Inversion Formula
X
Y
X
Y
IY
Design Quality Criteria
 How easily could your code be covered by unit
tests?
 Could web modules be used independently?
Class Dependencies
 Passive Injection
 Constructor
 Method
 Field
 Active Injection
 Service Locator
Module Dependencies
 Asynchronous Module Definition (AMD)
https://github.com/amdjs/amdjs-api/wiki/AMD
define(id?, depende...
RequireJS Module Sample
93
Web Modules Dependencies (1)
Web Modules Dependencies (2)
95
Models & Collections
Root View
View 1 View 2
View 1 View 1 View 1 View 1
For further reading…
1. JavaScript Good Parts
2. JavaScript Garden
3. Leaning JavaScript Design Patterns (by Addy Osmani)
...
Modern JavaScript Applications: Design Patterns
Upcoming SlideShare
Loading in...5
×

Modern JavaScript Applications: Design Patterns

21,473

Published on

It's presented how classical OOP approaches and design patterns can be used for modern JavaScript applications.

Published in: Software, Technology

Transcript of "Modern JavaScript Applications: Design Patterns"

  1. 1. MODERN JAVASCRIPT APPLICATIONS Volodymyr VoityshynRivne 2013
  2. 2. How to get well structured JavaScript code? How to get well structured JavaScript code?
  3. 3. Client JavaScript Evolution 1. Client JavaScript resolved auxiliary tasks 2. Single Page Web Applications 3. Real time applications 4
  4. 4. Contents I. Some Useful Constructions II. What is wrong? III. JavaScript & OOP IV. Module Pattern V. Object Oriented Design Patterns VI. MV* Patterns via BackboneJS VII. Dependencies Management 5
  5. 5. I. Some Useful Constructions
  6. 6. Closures 7
  7. 7. IIFE 8
  8. 8. Named Parameters Must be documented 9 It’s useful for 4 and more parameters
  9. 9. II. What is wrong?
  10. 10. Global Functions  Avoid global functions  Use instead:  Classes  Modules 11
  11. 11. Mixing JavaScript with HTML ▪ Place HTML and JavaScript in separated files ▪ Assign event handlers with JavaScript 12
  12. 12. Mixing JS & Server Code is Bad ASP.NET MVC Razor 13
  13. 13. Mixing JS & Server Code is Acceptable ASP.NET MVC Razor 14
  14. 14. III. JavaScript & OOP
  15. 15. Fact #1 Everything is an object 16
  16. 16. … even primitives and functions 17
  17. 17. Creating an Object 18
  18. 18. Fact # 2 Object members can be added/deleted dynamically 19
  19. 19. Defining Members 20
  20. 20. Creating an Object with JSON Notation 21
  21. 21. Deleting Members 22
  22. 22. Fact #3 All object members are public 23
  23. 23. Fact #4 Objects are hash tables 24
  24. 24. Access to a Property with [] 25
  25. 25. Fact #5 Inheritance is based on prototypes 26
  26. 26. Inheritance Object vehicle + name + run() bicycle + wheels Sample_2_01 27
  27. 27. Fact #6 Functions can be considered as classes 28
  28. 28. Pseudo Class Object Vehicle + name + run() 29
  29. 29. The “prototype” Property Object Vehicle + name + run() 30
  30. 30. Pseudo Class Inheritance Object Vehicle + name + run() Bicycle + wheels Sample_2_02 31
  31. 31. Inheritance: Practice Hints  Avoid a too long prototype chain  Avoid extending prototypes of built-in objects  Use framework functions for extending objects:  $.extend()  _.extend()  _.mixin() 32
  32. 32. Virtual Functions 33
  33. 33. Static Members 34
  34. 34. IV. Module Pattern
  35. 35. Module Pattern Intent Provides both private and public encapsulation for classes
  36. 36. Module Example ▪ Closure is used for private state ▪ “Public” object is returned ▪ Created by IIFE Sample_3_01_Module_Counter 37
  37. 37. Import Dependencies 38
  38. 38. Extending Sample_3_02_Module_Strings 39
  39. 39. Extending jQuery Module 40
  40. 40. Extending Underscore Module 41
  41. 41. Page Code Behind as Module Page (HTML + CSS) Code Behind (JavaScript Module) Handle Events Read Data Put Data 42 Sample_3_04_PageCodeBehind_Module
  42. 42. Advantages vs. Disadvantages  Advantages  Simple in development  Possibility of using a page base class  Disadvantages  Becomes too large in case of a complex page  Hard in automated testing  Can’t be used with SPA 43
  43. 43. Class as Module 44
  44. 44. V. Object Oriented Design Patterns
  45. 45. V.1. Creational Patterns “… help make a system independent of how its objects are created, composed, and represented” (GoF)
  46. 46. Factory Pattern Intent Provides an interface for creating families of related or dependent objects without specifying their concrete classes. (GoF)
  47. 47. Classical Abstract Factory AbstractComponentFactory - components + create(string) ChComponentFactory IEComponentFactory Calendar + render() IECalendar + render() ChCalendar + render() Grid + render() IEGrid + render() ChGrid + render() Sample_4_01_AbstractFactory_CrossBrowser_Component
  48. 48. Service Locator & IoC  Provides abstract interface for instantiating objects  Resolves dependencies among objects  Manages objects’ life cycle
  49. 49. Prototype Pattern Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. (GoF) Prototype New Object clone()
  50. 50. Prototype by Native JavaScript Object p id, name p1 p2
  51. 51. Prototype as a Shallow Copy Object p3 id, name p4 id, name p5 id, name
  52. 52. Prototype as a Deep Copy Object p6 id, name p7 id, name
  53. 53. Classical Prototype
  54. 54. Cloning DOM Elements
  55. 55. V.2. Structural Patterns “… are concerned with how classes and objects are composed to form larger structures” (GoF)
  56. 56. Adapter Pattern Intent Convert the interface of a class into another interface clients expect (GoF) Client Expected Interface Old Interface
  57. 57. Adapting to Underscore Interface
  58. 58. Decorator Pattern Intent Attach additional responsibilities to an object dynamically (GoF) Decorator 2 Decorator 1 an ObjectClient
  59. 59. Classical Decorator
  60. 60. Decorator and IIFE
  61. 61. Decorator with Closure
  62. 62. Façade Pattern Intent Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. (GoF) A Complex System Façade Client
  63. 63. Façade in jQuery XMLHttpRequest $.ajax() Client document.createElement() $(“<tag>”) Client
  64. 64. Façade: Important Consideration Performance Comfortable Interface
  65. 65. V.3. Behavioral Patterns “… are concerned with algorithms and the assignment of responsibilities among objects” (GoF)
  66. 66. Observer Pattern Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. (GoF) Subject Observer 1 Observer 2 Observer 3 Notify about changes Notify about changes
  67. 67. Publish/Subscribe
  68. 68. Publish/Subscribe & Backbone Event
  69. 69. Mediator Pattern Intent Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. (GoF)
  70. 70. Mediator as Event Buss Event Buss Module 1 Module 2 Publishes an event Listens an event http://thejacklawson.com/Mediator.js/ Transfers an event from the publisher to the listeners
  71. 71. Mediator as Web Modules Manager Web Module 1 Web Module 2 Web Modules Manager Nicholas Zakas: Scalable JavaScript Application Architecture  Manages a web module life cycle  Manages collaboration among modules Web Module Context  Everything a web module knows about the application  Manage user’s interaction  Don’t know about each other Web Module ↓ an independent part of GUI
  72. 72. Strategy Pattern Intent Define a family of algorithms, encapsulate each one, and make them interchangeable. (GoF)
  73. 73. Sorting Algorithms as Strategy
  74. 74. VI. MV* Patterns via BackboneJS
  75. 75. Model – View – Controller View Model Controller Main goal - separate view and data
  76. 76. Top JavaScript MVC Frameworks Knockout.js Ember.js Angular.js Backbone.js
  77. 77. Backbone Object Types 78  Events  Model  Collection  View  Router
  78. 78. Backbone.js Typical Stack Backbone.js Underscore.js jQuery Require.js
  79. 79. Backbone Advantages 80  Simple in usage  Defines major types of an application objects  Gets much freedom for application structure  Easily extensible  Gets on well with other frameworks
  80. 80. VII. Dependencies Management
  81. 81. What is a bad design?  Inflexibility  Fragility  Solidity
  82. 82. Coupling A measure of how much a module relies on other modules
  83. 83. Cohesion A measure of how closely related the members of a module are to the other members of the same module HighLow
  84. 84. What is a good design?  Flexible  Robust  Reusable
  85. 85. What’s a main problem?
  86. 86. What is a key to success? Manage dependencies!
  87. 87. Dependency Inversion Principle A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions. (Robert C. Martin) The Dependency Inversion Principle (by Robert C. Martin)
  88. 88. Dependency Inversion Formula X Y X Y IY
  89. 89. Design Quality Criteria  How easily could your code be covered by unit tests?  Could web modules be used independently?
  90. 90. Class Dependencies  Passive Injection  Constructor  Method  Field  Active Injection  Service Locator
  91. 91. Module Dependencies  Asynchronous Module Definition (AMD) https://github.com/amdjs/amdjs-api/wiki/AMD define(id?, dependencies?, factory)
  92. 92. RequireJS Module Sample 93
  93. 93. Web Modules Dependencies (1)
  94. 94. Web Modules Dependencies (2) 95 Models & Collections Root View View 1 View 2 View 1 View 1 View 1 View 1
  95. 95. For further reading… 1. JavaScript Good Parts 2. JavaScript Garden 3. Leaning JavaScript Design Patterns (by Addy Osmani) 4. JavaScript Module Pattern: In-Depth (by Ben Cherry) 5. Scalable JavaScript Application Architecture (by Nicholas Zakas) 6. Journey Through The JavaScript MVC Jungle (by Addy Osmani) 7. Developing Backbone.js Applications (by Addy Osmani) 8. superhero.js
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×