SlideShare a Scribd company logo
App創業與實作
App Entrepreneurship and implementation
                       Week 06
        Reusable Code at Clients: Layouts and MVC

                      吳尚鴻
                 (清大資工系專任教授)
                   (2013-03-28)

本授權條款允許使用者重製、散布、傳輸著作,但不得為商業目的之使用,亦不得修改該著作。
使用時必須按照著作人指定的方式表彰其姓名。
CC (Creative Commons)

姓名標示─非商業性─禁止改作

本授權條款允許使用者重製、散布、傳輸著作,但不得為商
業目的之使用,亦不得修改該著作。使用時必須按照著作人
指定的方式表彰其姓名。
Modular JavaScript

    Shan-Hung Wu
      CS, NTHU,
     Spring, 2013
Agenda
• The consequence of complex clients
• Object-oriented JavaScript
• Modular GUI: components, containers, and
  layouts
• Client-side MVC




                                             2
Agenda
• The consequence of complex clients
• Object-oriented JavaScript
• Modular GUI: components, containers, and
  layouts
• Client-side MVC




                                             3
Today’s JavaScript Clients are Very
            Complex




                                      4
Can you write JavaScript like that?




                                      5
The Missing Topics
• Object-oriented JavaScript
  – Writing reusable classes
• Modular GUI: components, containers, and
  layouts
  – Writing assemblable GUI components
• Client-side MVC
  – Maintaining tractable projects


                                             6
Agenda
• The consequence of complex clients
• Object-oriented JavaScript
• Modular GUI: components, containers, and
  layouts
• Client-side MVC




                                             7
Why OOP in JavaScript?




                         8
You Want This
                        Toolbar




          MailToolbar             CalendarToolbar



• Pros:
  – Reusable code in Toolbar


                                                    9
Function Objects: A Review
• In JavaScript, functions are objects
  1. var User = function() {
  2. this.name = ...
  3. };
  4. // as object
  5. User.name = ...;
  6. // as function
  7. var ret = User();
  8. // as constructor
  9. var usr = new User();

• What does it really mean?

                                         10
Homework: the memory scheme?
           1. var obj = new Object();
           2. obj.x = 1;
           3. obj.y = 2;
           4.
           5. var User = function(name) {
           6.    this.name = name;
           7. };
           8. var usr = new User();




                                            11
Memory Scheme
1.   var obj = new Object();                Object             prototype
2.   obj.x = 1;
                                   prototype : object   __proto__ : object
3.   obj.y = 2;
                                                        constructor: function
4.
5.   var User = function(name) {
6.      this.name = name;                     obj
7.   };                            __proto__ : object
8.   var usr = new User();         x: number
                                   y: number

• __proto__ is not
  accessible directly                       User               prototype
      – Only through               prototype : object   __proto__ : object
        Object.prototype                                constructor: function


• Different objs reference
                                             usr
  the same prototype
  object                           __proto__ : object
                                   name: string



                                                                                12
Prototype Chain
1.   var obj = new Object();                Object             prototype
2.   obj.x = 1;
                                   prototype : object   __proto__ : object
3.   obj.y = 2;
                                                        constructor: function
4.
5.   var User = function(name) {
6.      this.name = name;                     obj
7.   };                            __proto__ : object
8.   var usr = new User();         x: number
                                   y: number

• Members of an
  object are sought                         User               prototype

  along the prototype              prototype : object   __proto__ : object
                                                        constructor: function
  chain from bottom
  up                                         usr

      – The first reached          __proto__ : object
        wins                       name: string



                                                                                13
OOP Goals
• Inheritance
   – The ability to define the behavior of one object in terms of
     another by sub-classing
• Polymorphism
   – The ability for two classes to respond to the same
     (collection of) methods
• Encapsulation
   – Hidden details via private members
   – Not recommended since
      • Bad performance
      • The benefits of using private members is rather limited in the
        context of JavaScript (which is already lacking any form of type
        safety)

                                                                           14
OK, so how to define a subclass of
User?




                                     15
Classing & Subclassing
1.    var User = function(name) {
2.       this.name = name;
                                                             Object              prototype
3.    };
4.    // define method (why in prototype?)           prototype : object   __proto__ : object
5.    User.prototype.getName = function() {                               constructor: function
6.       return this.name;
7.    }
8.
9.    var usr = new User();                                   User               prototype
10.   alert(usr instanceof User); // true
11.   alert(usr.getName());                          prototype : object   __proto__ : object
12.                                                                       Constructor : function
                                                                          getName : function
13.   // define subclass
14.   Var Vip = function(name, title) {
15.      User.call(this);                                      usr
16.      this.title = title;
17.   }                                              __proto__ : object
                                                     name: string
18.   Vip.prototype = new User();
19.   Vip.prototype.constructor = Vip;
20.   // override method
21.   Vip.prototype.getName = function() {
22.      // if necessary: User.prototype.getName()             Vip               prototype
23.      //       .call(this);
24.      return title + ': ' + name;                 prototype : object   __proto__ : object
25.   }                                                                   constructor: function
                                                                          getName : function

26.   usr = new Vip(...);
27.   alert(usr instanceof Vip); // true                       usr
28.   alert(usr instanceof User); // true            __proto__ : object
29.   alert(usr.getName()); // polymorphism          name: string
                                                     title: string                                 16
Reusing Toolbar




                  17
You Can Do This
                         Toolbar




          MailToolbar              CalendarToolbar


• Toolbar:
  – Basic look, button events
• MailToolbar and CalendarToolbar:
  – Buttons, event handler, and specialized look

                                                     18
Homework
• How to define static members of a class?




                                             19
Agenda
• The consequence of complex clients
• Object-oriented JavaScript
• Modular GUI: components, containers, and
  layouts
• Client-side MVC




                                             20
Components, Containers, and Layouts




2013/3/28                          21
Containing Relationship vs.
                Is-a Relationship
• Containing
  relationship ≠ is-a
  Relationship
• Containing
  relationship
                          Component       Layout
      – Between
        components
      – Visual level
• Is-a relationship       Container

      – Between classes
      – Code level

2013/3/28                                          22
Page Life Cycle
                 • onReady
                 • Init. objects and
                   their members                    Adjust relative sizing & placing




• Load scripts
• Class system                         • Component -> HTML
• Dom Ready                            • Downward recursively

                                                                               23
Initialization
• Right after the onReady() function is called
• Each component and container should be
  constructed and wired together




2013/3/28                                    24
Render
• Convert initialized components and containers
  to html
• Downward along the containing relationship
  by recursively calling(), for example,
  onRender()




2013/3/28                                     25
Layout
• Positioning, sizing, and CSS calculation
  between each container and its containing
  components
      – Upward recursively
      – Done by the layout object associated with each
        container
• Every time the layout changed, DOM will re-
  compute all elements in the site.

2013/3/28                                                26
Agenda
• The consequence of complex clients
• Object-oriented JavaScript
• Modular GUI: components, containers, and
  layouts
• Client-side MVC




                                             27
What is MVC?




               28
Why do we need MVC at clients?




                                 29
Think about
     Data
• Despite of protocols
  (SOAP, REST, etc.), you
  want to store data
  obtained from server
  – Saves time if two components share the same
    data
  – Also reduces server load
• What if one component change the data?
  – How to notify another component?

                                                  30
Trick
1. Define JS objects that represent/wrap the
   data
2. Allow these objects to fire events (e.g.,
   data_changed(oldVal, newVal))
3. Let Component objects listen to these data
   events



                                                31
Good design?
A component is not reusable anymore
as it is dependent to data



                                      32
Client-side MVC
• Model is a collection of objects reflecting data and their
  fields
   – Fire data-related events
   – Relational model at client-side
   – Can define advanced classes to ease data manipulation, e.g.,
     searcher
• View is a collection of component
   – E.g., Grids, trees, toolbar, etc.
   – Fires view-related events
• Controllers bind views and models together
   – Listen to events from both views and models and handle them
• Pros?


                                                                    33
An Example Project Structure
                               Application name




                                MVC files




Application start point


                                                  34
Q&A




      35

More Related Content

PPTX
Javascript Common Design Patterns
PPT
Advanced Javascript
PPTX
Advanced JavaScript
PDF
(3) cpp abstractions more_on_user_defined_types
KEY
みゆっき☆Think#7 「本気で学ぶJavascript」
KEY
Parte II Objective C
PDF
Lecture 04
PDF
Objective-C for Java Developers
Javascript Common Design Patterns
Advanced Javascript
Advanced JavaScript
(3) cpp abstractions more_on_user_defined_types
みゆっき☆Think#7 「本気で学ぶJavascript」
Parte II Objective C
Lecture 04
Objective-C for Java Developers

What's hot (19)

PDF
Iphone course 1
PDF
Future-proofing Your JavaScript Apps (Compact edition)
KEY
JavaScript Growing Up
PDF
안드로이드 데이터 바인딩
PDF
Objective-C for Beginners
PPTX
Enterprise js pratices
KEY
2012 oct-12 - java script inheritance
PDF
Descriptor Protocol
PDF
iPhone Seminar Part 2
PPTX
From C++ to Objective-C
PPTX
Chapter iii(oop)
KEY
Runtime
PDF
Java Script Best Practices
PPT
Advanced JavaScript
PPTX
Object Oriented JavaScript
PDF
Automatically generating-json-from-java-objects-java-objects268
PPTX
YUI Tidbits
KEY
A tour on ruby and friends
DOCX
Exercícios Netbeans - Vera Cymbron
Iphone course 1
Future-proofing Your JavaScript Apps (Compact edition)
JavaScript Growing Up
안드로이드 데이터 바인딩
Objective-C for Beginners
Enterprise js pratices
2012 oct-12 - java script inheritance
Descriptor Protocol
iPhone Seminar Part 2
From C++ to Objective-C
Chapter iii(oop)
Runtime
Java Script Best Practices
Advanced JavaScript
Object Oriented JavaScript
Automatically generating-json-from-java-objects-java-objects268
YUI Tidbits
A tour on ruby and friends
Exercícios Netbeans - Vera Cymbron
Ad

Viewers also liked (7)

PDF
Ubitus unlocking the_true_potential_of_cloud_gaming
PDF
Week 15 - Scaling & Security_Jim Huang
PDF
Week 03 Whoscall's Story_Jeff Kuo (2013 03-07)
PDF
Week 17 - Going All The Way_Jason Ho
PDF
Week 12 - Ubitus → Google_Victor Shen
PDF
Week 16 - appWorks_IC Jan
PDF
The0 step 尋找推動成功方程式
Ubitus unlocking the_true_potential_of_cloud_gaming
Week 15 - Scaling & Security_Jim Huang
Week 03 Whoscall's Story_Jeff Kuo (2013 03-07)
Week 17 - Going All The Way_Jason Ho
Week 12 - Ubitus → Google_Victor Shen
Week 16 - appWorks_IC Jan
The0 step 尋找推動成功方程式
Ad

Similar to Week 06 Modular Javascript_Brandon, S. H. Wu (20)

PDF
Prototype-based Programming with JavaScript
PDF
運用Closure Compiler 打造高品質的JavaScript
PDF
The many facets of code reuse in JavaScript
KEY
Javascript tid-bits
PPTX
Object oriented javascript
PPT
Javascript Object Oriented Programming
KEY
第7回みゆっき☆Think 本気で学ぶ JavaScript
PDF
JavaScript 101
PDF
JavaScript 1.5 to 2.0 (TomTom)
PPT
Beginning Object-Oriented JavaScript
PPT
Advanced JavaScript
PDF
Professional JavaScript Development - Creating Reusable Code
PDF
Tamarin And Ecmascript 4
PDF
Prototype
KEY
Dojo for programmers (TXJS 2010)
KEY
Inheritance patterns
PDF
The Future of JavaScript (Ajax Exp '07)
PDF
JavaScript Core
PDF
JS Level Up: Prototypes
PPTX
JavsScript OOP
Prototype-based Programming with JavaScript
運用Closure Compiler 打造高品質的JavaScript
The many facets of code reuse in JavaScript
Javascript tid-bits
Object oriented javascript
Javascript Object Oriented Programming
第7回みゆっき☆Think 本気で学ぶ JavaScript
JavaScript 101
JavaScript 1.5 to 2.0 (TomTom)
Beginning Object-Oriented JavaScript
Advanced JavaScript
Professional JavaScript Development - Creating Reusable Code
Tamarin And Ecmascript 4
Prototype
Dojo for programmers (TXJS 2010)
Inheritance patterns
The Future of JavaScript (Ajax Exp '07)
JavaScript Core
JS Level Up: Prototypes
JavsScript OOP

More from AppUniverz Org (6)

PDF
Week 11 - KKBOX_Eric Tsai
PDF
Week 08 Cloud_Eric Shangkuan
PDF
Week 05 Web, App and Javascript_Brandon, S.H. Wu
PDF
Week 04 Web Development Flow and Fast Prototyping_hlb (2013-03-14)
PDF
Appuniverz 回顧與展望
PDF
[課程介紹] App創業與實作
Week 11 - KKBOX_Eric Tsai
Week 08 Cloud_Eric Shangkuan
Week 05 Web, App and Javascript_Brandon, S.H. Wu
Week 04 Web Development Flow and Fast Prototyping_hlb (2013-03-14)
Appuniverz 回顧與展望
[課程介紹] App創業與實作

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Institutional Correction lecture only . . .
PDF
Computing-Curriculum for Schools in Ghana
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Classroom Observation Tools for Teachers
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
O5-L3 Freight Transport Ops (International) V1.pdf
VCE English Exam - Section C Student Revision Booklet
Anesthesia in Laparoscopic Surgery in India
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Institutional Correction lecture only . . .
Computing-Curriculum for Schools in Ghana
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Sports Quiz easy sports quiz sports quiz
GDM (1) (1).pptx small presentation for students
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
01-Introduction-to-Information-Management.pdf
Cell Structure & Organelles in detailed.
Classroom Observation Tools for Teachers
TR - Agricultural Crops Production NC III.pdf
RMMM.pdf make it easy to upload and study
102 student loan defaulters named and shamed – Is someone you know on the list?
PPH.pptx obstetrics and gynecology in nursing
human mycosis Human fungal infections are called human mycosis..pptx

Week 06 Modular Javascript_Brandon, S. H. Wu

  • 1. App創業與實作 App Entrepreneurship and implementation Week 06 Reusable Code at Clients: Layouts and MVC 吳尚鴻 (清大資工系專任教授) (2013-03-28) 本授權條款允許使用者重製、散布、傳輸著作,但不得為商業目的之使用,亦不得修改該著作。 使用時必須按照著作人指定的方式表彰其姓名。
  • 3. Modular JavaScript Shan-Hung Wu CS, NTHU, Spring, 2013
  • 4. Agenda • The consequence of complex clients • Object-oriented JavaScript • Modular GUI: components, containers, and layouts • Client-side MVC 2
  • 5. Agenda • The consequence of complex clients • Object-oriented JavaScript • Modular GUI: components, containers, and layouts • Client-side MVC 3
  • 6. Today’s JavaScript Clients are Very Complex 4
  • 7. Can you write JavaScript like that? 5
  • 8. The Missing Topics • Object-oriented JavaScript – Writing reusable classes • Modular GUI: components, containers, and layouts – Writing assemblable GUI components • Client-side MVC – Maintaining tractable projects 6
  • 9. Agenda • The consequence of complex clients • Object-oriented JavaScript • Modular GUI: components, containers, and layouts • Client-side MVC 7
  • 10. Why OOP in JavaScript? 8
  • 11. You Want This Toolbar MailToolbar CalendarToolbar • Pros: – Reusable code in Toolbar 9
  • 12. Function Objects: A Review • In JavaScript, functions are objects 1. var User = function() { 2. this.name = ... 3. }; 4. // as object 5. User.name = ...; 6. // as function 7. var ret = User(); 8. // as constructor 9. var usr = new User(); • What does it really mean? 10
  • 13. Homework: the memory scheme? 1. var obj = new Object(); 2. obj.x = 1; 3. obj.y = 2; 4. 5. var User = function(name) { 6. this.name = name; 7. }; 8. var usr = new User(); 11
  • 14. Memory Scheme 1. var obj = new Object(); Object prototype 2. obj.x = 1; prototype : object __proto__ : object 3. obj.y = 2; constructor: function 4. 5. var User = function(name) { 6. this.name = name; obj 7. }; __proto__ : object 8. var usr = new User(); x: number y: number • __proto__ is not accessible directly User prototype – Only through prototype : object __proto__ : object Object.prototype constructor: function • Different objs reference usr the same prototype object __proto__ : object name: string 12
  • 15. Prototype Chain 1. var obj = new Object(); Object prototype 2. obj.x = 1; prototype : object __proto__ : object 3. obj.y = 2; constructor: function 4. 5. var User = function(name) { 6. this.name = name; obj 7. }; __proto__ : object 8. var usr = new User(); x: number y: number • Members of an object are sought User prototype along the prototype prototype : object __proto__ : object constructor: function chain from bottom up usr – The first reached __proto__ : object wins name: string 13
  • 16. OOP Goals • Inheritance – The ability to define the behavior of one object in terms of another by sub-classing • Polymorphism – The ability for two classes to respond to the same (collection of) methods • Encapsulation – Hidden details via private members – Not recommended since • Bad performance • The benefits of using private members is rather limited in the context of JavaScript (which is already lacking any form of type safety) 14
  • 17. OK, so how to define a subclass of User? 15
  • 18. Classing & Subclassing 1. var User = function(name) { 2. this.name = name; Object prototype 3. }; 4. // define method (why in prototype?) prototype : object __proto__ : object 5. User.prototype.getName = function() { constructor: function 6. return this.name; 7. } 8. 9. var usr = new User(); User prototype 10. alert(usr instanceof User); // true 11. alert(usr.getName()); prototype : object __proto__ : object 12. Constructor : function getName : function 13. // define subclass 14. Var Vip = function(name, title) { 15. User.call(this); usr 16. this.title = title; 17. } __proto__ : object name: string 18. Vip.prototype = new User(); 19. Vip.prototype.constructor = Vip; 20. // override method 21. Vip.prototype.getName = function() { 22. // if necessary: User.prototype.getName() Vip prototype 23. // .call(this); 24. return title + ': ' + name; prototype : object __proto__ : object 25. } constructor: function getName : function 26. usr = new Vip(...); 27. alert(usr instanceof Vip); // true usr 28. alert(usr instanceof User); // true __proto__ : object 29. alert(usr.getName()); // polymorphism name: string title: string 16
  • 20. You Can Do This Toolbar MailToolbar CalendarToolbar • Toolbar: – Basic look, button events • MailToolbar and CalendarToolbar: – Buttons, event handler, and specialized look 18
  • 21. Homework • How to define static members of a class? 19
  • 22. Agenda • The consequence of complex clients • Object-oriented JavaScript • Modular GUI: components, containers, and layouts • Client-side MVC 20
  • 23. Components, Containers, and Layouts 2013/3/28 21
  • 24. Containing Relationship vs. Is-a Relationship • Containing relationship ≠ is-a Relationship • Containing relationship Component Layout – Between components – Visual level • Is-a relationship Container – Between classes – Code level 2013/3/28 22
  • 25. Page Life Cycle • onReady • Init. objects and their members Adjust relative sizing & placing • Load scripts • Class system • Component -> HTML • Dom Ready • Downward recursively 23
  • 26. Initialization • Right after the onReady() function is called • Each component and container should be constructed and wired together 2013/3/28 24
  • 27. Render • Convert initialized components and containers to html • Downward along the containing relationship by recursively calling(), for example, onRender() 2013/3/28 25
  • 28. Layout • Positioning, sizing, and CSS calculation between each container and its containing components – Upward recursively – Done by the layout object associated with each container • Every time the layout changed, DOM will re- compute all elements in the site. 2013/3/28 26
  • 29. Agenda • The consequence of complex clients • Object-oriented JavaScript • Modular GUI: components, containers, and layouts • Client-side MVC 27
  • 31. Why do we need MVC at clients? 29
  • 32. Think about Data • Despite of protocols (SOAP, REST, etc.), you want to store data obtained from server – Saves time if two components share the same data – Also reduces server load • What if one component change the data? – How to notify another component? 30
  • 33. Trick 1. Define JS objects that represent/wrap the data 2. Allow these objects to fire events (e.g., data_changed(oldVal, newVal)) 3. Let Component objects listen to these data events 31
  • 34. Good design? A component is not reusable anymore as it is dependent to data 32
  • 35. Client-side MVC • Model is a collection of objects reflecting data and their fields – Fire data-related events – Relational model at client-side – Can define advanced classes to ease data manipulation, e.g., searcher • View is a collection of component – E.g., Grids, trees, toolbar, etc. – Fires view-related events • Controllers bind views and models together – Listen to events from both views and models and handle them • Pros? 33
  • 36. An Example Project Structure Application name MVC files Application start point 34
  • 37. Q&A 35