SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
JavaScript Patterns: Spaghetti to Ravioli
John Papa
@john_papa
http://johnpapa.net
Outline
 Spaghetti and Ravioli



Separation Patterns
Avoiding Globals

 Object Literals
 Module Pattern




Anonymous Closures
Private/Public Members
Immediate Invocation

 Revealing Module Pattern


Refinements to Module Pattern
Function Spaghetti Code
- Wikipedia: http://jpapa.me/spaghetticode
Problems with Spaghetti Code








Mixing of Concerns
No clear separation of functionality or purpose
Variables/functions added into global scope
Potential for duplicate function names
Not modular
Not easy to maintain
No sense of a “container”
Some Examples of Spaghetti Code with JavaScript







Script all over the page
Objects are extended in many places in no discernible pattern
Everything is a global function
Functions are called in odd places
Everything is a global
Heavy JavaScript logic inside HTML attributes



Obtrusive JavaScript
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
Advantages of Ravioli Code
 Objects encapsulate and decouple code
 Easy to extend and maintain
 Separation of Concerns



Variables/functions are scoped
Functionality in closures
Namespaces
 Encapsulate your code under a namespace
 Avoid collisions
 First and easy step towards Ravioli’s
var my = my || {};

my.viewmodel = function(){

}
DEMO
Namespaces and Separation
Outline





Spaghetti and Ravioli
Object Literals
Module Pattern
Revealing Module Pattern
Object Literals
 Benefits
 Quick and easy
 All members are available
 Challenges
 “this” problems
 Best suited for simple view models and data
my.viewmodel = {
name: ko.observable(),
price: function(x, y){
return x + y;
}
};
DEMO
ViewModel as an Object Literal
Outline





Spaghetti and Ravioli
Object Literals
Module Pattern
Revealing Module Pattern
Module Pattern
 Anonymous Closures


Functions for encapsulation

 Immediate function invocation
 Private and public members
Anonymous Closure
 Function expression instead of function definition


Wrapped in parens

 Scoped


All vars and functions are enclosed

(function () {
}());
Immediate Function Invocation
 Create a module
 Immediately available
my.viewmodel = (function(){
var tempValue = 1;
return {
someVal: "john",
add: function(x, y){
this.tempValue = x;
return x + y;
};
};
})();

Immediate instantiation
Private/Public Members
Private member
var my.viewmodel = (function(){
var privateVal = 3;
return {
publicVal: 7,
add: function(x, y){
var x = this.publicVal + privateVal;
return x + y;
};
};
})();

Public members

Accessing private
members with ‘this’
The Module Pattern
 Benefits:





Modularize code into re-useable objects
Variables/functions taken out of global namespace
Expose only public members
Hide plumbing code

 Challenges:


Access public and private members differently
DEMO
ViewModel as a Module
Outline





Spaghetti and Ravioli
Object Literals
Module Pattern
Revealing Module Pattern
The Revealing Module Pattern
 All the Benefits of the Module Patterns +


Makes it clear what is public vs private



Helps clarify "this"



Reveal private functions with different names
Revealing
my.viewmodel = (function(){
var privateVal = 3,
add: function(x, y){
return x + y;
};
return {
someVal: privateVal,
add: add
};
};
})();

Private members

Public members
DEMO
ViewModel as a Revealing Module
Summary
 Spaghetti and Ravioli




Avoid globals
Avoid function spaghetti code
Separation of presentation, structure, and behavior

 3 ViewModel Patterns




Object Literals
Module Pattern
Revealing Module Pattern

Spaghetti to Ravioli
For more in-depth online developer training visit

on-demand content from authors you trust

Weitere ähnliche Inhalte

Ähnlich wie Knockout mvvm-m4-slides

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 

Ähnlich wie Knockout mvvm-m4-slides (20)

Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
KMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScriptKMS TechCon 2014 - Interesting in JavaScript
KMS TechCon 2014 - Interesting in JavaScript
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
SOLID
SOLIDSOLID
SOLID
 
Built to last javascript for enterprise
Built to last   javascript for enterpriseBuilt to last   javascript for enterprise
Built to last javascript for enterprise
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Design pattern
Design patternDesign pattern
Design pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Building Scalable JavaScript Apps
Building Scalable JavaScript AppsBuilding Scalable JavaScript Apps
Building Scalable JavaScript Apps
 
Csci360 20 (1)
Csci360 20 (1)Csci360 20 (1)
Csci360 20 (1)
 
Csci360 20
Csci360 20Csci360 20
Csci360 20
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
JavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersJavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint Developers
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
Working with AngularJS
Working with AngularJSWorking with AngularJS
Working with AngularJS
 

Mehr von MasterCode.vn

Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
MasterCode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
MasterCode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
MasterCode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
MasterCode.vn
 

Mehr von MasterCode.vn (20)

Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vnPd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
 
Why apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vnWhy apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vn
 
Dzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vnDzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vn
 
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vnGoogle công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
 
Nghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vnNghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vn
 
Lập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vnLập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vn
 
Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
 
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vnPd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
 
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vnPd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
 
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vnPdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
 
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vnPdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vnPdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vnPdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vnPdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vnPdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vnPdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vnPdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Kürzlich hochgeladen (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Knockout mvvm-m4-slides

  • 1. JavaScript Patterns: Spaghetti to Ravioli John Papa @john_papa http://johnpapa.net
  • 2. Outline  Spaghetti and Ravioli   Separation Patterns Avoiding Globals  Object Literals  Module Pattern    Anonymous Closures Private/Public Members Immediate Invocation  Revealing Module Pattern  Refinements to Module Pattern
  • 3. Function Spaghetti Code - Wikipedia: http://jpapa.me/spaghetticode
  • 4. Problems with Spaghetti Code        Mixing of Concerns No clear separation of functionality or purpose Variables/functions added into global scope Potential for duplicate function names Not modular Not easy to maintain No sense of a “container”
  • 5. Some Examples of Spaghetti Code with JavaScript       Script all over the page Objects are extended in many places in no discernible pattern Everything is a global function Functions are called in odd places Everything is a global Heavy JavaScript logic inside HTML attributes   Obtrusive JavaScript http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
  • 6. Advantages of Ravioli Code  Objects encapsulate and decouple code  Easy to extend and maintain  Separation of Concerns   Variables/functions are scoped Functionality in closures
  • 7. Namespaces  Encapsulate your code under a namespace  Avoid collisions  First and easy step towards Ravioli’s var my = my || {}; my.viewmodel = function(){ }
  • 9. Outline     Spaghetti and Ravioli Object Literals Module Pattern Revealing Module Pattern
  • 10. Object Literals  Benefits  Quick and easy  All members are available  Challenges  “this” problems  Best suited for simple view models and data my.viewmodel = { name: ko.observable(), price: function(x, y){ return x + y; } };
  • 11. DEMO ViewModel as an Object Literal
  • 12. Outline     Spaghetti and Ravioli Object Literals Module Pattern Revealing Module Pattern
  • 13. Module Pattern  Anonymous Closures  Functions for encapsulation  Immediate function invocation  Private and public members
  • 14. Anonymous Closure  Function expression instead of function definition  Wrapped in parens  Scoped  All vars and functions are enclosed (function () { }());
  • 15. Immediate Function Invocation  Create a module  Immediately available my.viewmodel = (function(){ var tempValue = 1; return { someVal: "john", add: function(x, y){ this.tempValue = x; return x + y; }; }; })(); Immediate instantiation
  • 16. Private/Public Members Private member var my.viewmodel = (function(){ var privateVal = 3; return { publicVal: 7, add: function(x, y){ var x = this.publicVal + privateVal; return x + y; }; }; })(); Public members Accessing private members with ‘this’
  • 17. The Module Pattern  Benefits:     Modularize code into re-useable objects Variables/functions taken out of global namespace Expose only public members Hide plumbing code  Challenges:  Access public and private members differently
  • 19. Outline     Spaghetti and Ravioli Object Literals Module Pattern Revealing Module Pattern
  • 20. The Revealing Module Pattern  All the Benefits of the Module Patterns +  Makes it clear what is public vs private  Helps clarify "this"  Reveal private functions with different names
  • 21. Revealing my.viewmodel = (function(){ var privateVal = 3, add: function(x, y){ return x + y; }; return { someVal: privateVal, add: add }; }; })(); Private members Public members
  • 22. DEMO ViewModel as a Revealing Module
  • 23. Summary  Spaghetti and Ravioli    Avoid globals Avoid function spaghetti code Separation of presentation, structure, and behavior  3 ViewModel Patterns    Object Literals Module Pattern Revealing Module Pattern Spaghetti to Ravioli
  • 24. For more in-depth online developer training visit on-demand content from authors you trust