SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
JavaScript and UI Architecture
        Best Practices
          Siarhei Barysiuk
   s.barysiuk@sam-solutions.net
Our roadmap
Introduction: What will we cover today?

• Coding patterns
  JavaScript-specific best practices
• Design patterns
  Language independent patterns, UI architecture
Coding patterns
Namespaces
Tip of the day

           “Global variables should be avoided in order to
           lower the possibility of variable naming
           collisions. “
Namespaces: Defining namespace

//defining top-level package
var MyApp = MyApp || {};

                                     //defining package
//defining package
                                     MyApp.dom = {
MyApp.string = MyApp.string || {};
                                     	 addEventListener: function(element,
//defining package
                                                                  callback) {
MyApp.string.utils = {
                                     	 	 //code goes here
	 trim: function(str) {
                                     	 },
	 	 //code goes here
                                     	 removeEventListener: function(element,
	 },
                                                                     callback) {
	 reverse: function(str) {
                                     	 	 //code goes here
	 	 //code goes here
                                     	 }	
	}
                                     };
};
Namespaces: Usage in code
MyApp.string.utils.reverse(...);
MyApp.string.utils.trim(...);

MyApp.dom.addEventListener(...);
MyApp.dom.removeEventListener(...);
Namespaces: namespace() function
//defining top-level package
var MyApp = MyApp || {};

//defines package structure
MyApp.namespace = function(name) {
	 if(name) {
	 	 //some checks if name is valid
	 	 var names = name.split(quot;.quot;);
	 	 var current = MyApp;
		
	 	 for(var i in names) {
	 	 	 if(!current[names[i]]) {
	 	 	 	 current[names[i]] = {};
			}
	 	 	 current = current[names[i]];
		}
		
	 	 return true;
	}
	 return false;
};
Namespaces: Defining namespace

//defining top-level package
var MyApp = MyApp || {};

//defining package                   //defining package
MyApp.string = MyApp.string || {};   MyApp.namespace(quot;string.utilsquot;);
//defining package                   //defining package
MyApp.string.utils = {               MyApp.string.utils.trim = function(str) {
	 trim: function(str) {              	 	 //code goes here
	 	 //code goes here                 	 	 console.log(quot;trimquot;);
	 },                                 	 };
	 reverse: function(str) {           	
	 	 //code goes here                 MyApp.string.utils.reverse = function(str) {
	}                                   	 	 //code goes here
};                                   	 	 console.log(quot;reversequot;);
                                     	 };
Questions?
Init-time branching
Tip of the day

          “Branch some parts of the browser-specific code
          during initialization, when the script loads, rather
          than during runtime to avoid performance hit.”
Init-time branching: Defining browser-specific methods
 MyApp.namespace(quot;domquot;);
 MyApp.dom.addListener = null;

 //all major browsers
 if(typeof window.addEventListener === 'function') {
 	   MyApp.dom.addListener = function(el, type, fn) {
         el.addEventListener(type, fn, false);
      };
 }
 //IE
 else if(typeof document.attachEvent === 'function') {
 	   MyApp.dom.addListener = function(el, type, fn) {
         el.attachEvent('on' + type, fn);
      };
 }
 //older browsers
 else {
 	   MyApp.dom.addListener = function(el, type, fn) {
         el['on' + type] = fn;
      };
 }
Questions?
Lazy definition
Tip of the day

          “The lazy definition pattern is very similar to the
          previous init-time branching pattern.

          The difference is that the branching happens only
          when the function is called for the first time.”
Lazy definition: Defining browser-specific methods
var MyApp = MyApp || {};
                                                          Override function first time
MyApp.dom = {
   addListener: function(el, type, fn){
     if (typeof el.addEventListener === 'function') {
       MyApp.dom.addListener = function(el, type, fn) {
           el.addEventListener(type, fn, false);
       };
     } else if (typeof el.attachEvent === 'function'){
       MyApp.dom.addListener = function(el, type, fn) {
           el.attachEvent('on' + type, fn);
       };
     } else {
       MyApp.dom.addListener = function(el, type, fn) {
           el['on' + type] = fn;
       };
     }
     MyApp.dom.addListener(el, type, fn);
   }
};
Questions?
Configuration object
Tip of the day

          “Instead of having many parameters, you can use
          one parameter and make it an object.

          The properties of the object are the actual
          parameters.”
Configuration object: Ordinary constructor
var MyApp = MyApp || {};
MyApp.namespace(quot;domquot;);

MyApp.dom.Button = function(text, type) {
    //some code here
}


MyApp.dom.Button = function(text, type, color, border, font) {
    //some code here
}
Configuration object: Usage of configuration object
var MyApp = MyApp || {};
MyApp.namespace(quot;domquot;);

MyApp.dom.Button = function(text, settings) {
	 var type = settings.type || 'submit';
  	var font =settings.font ||'Verdana';
	 //..other props
		
    //some code here
}
Questions?
Private properties and methods
Tip of the day

           “Use local variables and methods inside a
           constructor to achieve the “private” level of
           protection.

           Use naming conventions _doInternalOperation to
           show that the function is private/protected.”
Private methods and properties: Private method
 var MyApp = MyApp || {};
 MyApp.namespace(quot;domquot;);

 MyApp.dom.Button = function(text, settings) {
 	   //..process properties
 	
 	   function setStyle(element, settings) {
 	   	   //setting style to element
 	   };
 	
     var button = //...
 	   //..
 	
 	   setStyle(button,settings);
 	
 	   this.clone = function() {
 	   	   var clonedButton = //...
 	   	   //...
 	   	
 	   	   setStyle(clonedButton, settings);
 	   }
 	   	
     //some code here
 }
Questions?
Self-executing functions
Tip of the day

           “Self-executing functions are especially suitable for
           one-off initialization tasks performed when the
           script loads.”
Self-executing functions: Usage
 (function() {
 	 //code goes here
 })();


 (function(){
 	 // ...
 	 var jQuery = window.jQuery = window.$ = function( selector, context ) {
 	 	 // ...
 	 	 return new jQuery.fn.init( selector, context );
 	 };
 	 // ...
 	 jQuery.fn = jQuery.prototype = {
 	 	 init: function() {
 	 	 	 //...
 		}
 	 };
 	
 })();
Questions?
Chaining
Tip of the day

           “Pretty convenient way to call several related
           methods on one line as if the methods are the links
           in a chain.”
Chaining: Usage
var obj = new MyApp.dom.Element('span');   var obj = new MyApp.dom.Element('span');

obj.setText('hello');                      obj.setText('hello')
obj.setStyle('color', 'red');                 .setStyle('color', 'red')
obj.setStyle('font', 'Verdana');              .setStyle('font', 'Verdana');

document.body.appendChild(obj);            document.body.appendChild(obj);



document.body.appendChild(
    new MyApp.dom.Element('span')
            .setText('hello')
            .setStyle('color', 'red')
            .setStyle('font', 'Verdana')
);
Questions?
Design patterns
Unobtrusive JavaScript
Unobtrusive JavaScript: Separate JavaScript functionality

     <a onclick=quot;doSomething()quot; href=quot;#quot;>Click!</a>




     <a href=quot;backuplink.htmlquot; class=quot;doSomethingquot;>Click!</a>

     $('a.doSomething').click(function(){
         // Do something here!
         alert('You did something, woo hoo!');
     });
Unobtrusive JavaScript: Never depend on JavaScript

    <script type=quot;text/javascriptquot;>
    	   var now = new Date();
    	   if(now.getHours() < 12)
    	   	   document.write('Good Morning!');
    	   else
    	   	   document.write('Good Afternoon!');
    </script>




    <p title=quot;Good Day Messagequot;>Good Morning!</p>

    var now = new Date();
    if(now.getHours() >= 12)
    {
    	 var goodDay = $('p[title=quot;Good Day Messagequot;]');
    	 goodDay.text('Good Afternoon!');
    }
Unobtrusive JavaScript: Never depend on JavaScript

    <a href=quot;javascript:window.open('page.html')quot;>my page</a>



    <a href=quot;#quot; onclick=quot;window.open('page.html')quot;>my page</a>



    <a href=quot;page.htmlquot; onclick=quot;window.open(this.href)quot;>my page</a>



    <a href=quot;page.htmlquot; class=quot;popupquot;>my page</a>
    //some java script to open element with class quot;.popupquot; in a new window
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 

Was ist angesagt? (20)

Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Keeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and WebpackKeeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and Webpack
 
Java script
Java scriptJava script
Java script
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practices
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 

Andere mochten auch

Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
Suresh Patidar
 
Modern UX, UI, and front-end tools
Modern UX, UI, and front-end toolsModern UX, UI, and front-end tools
Modern UX, UI, and front-end tools
Alan Roy
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
Damien Seguy
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuning
Andy Pemberton
 

Andere mochten auch (20)

Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
Pattern oriented architecture for web based architecture
Pattern oriented architecture for web based architecturePattern oriented architecture for web based architecture
Pattern oriented architecture for web based architecture
 
Modern UX, UI, and front-end tools
Modern UX, UI, and front-end toolsModern UX, UI, and front-end tools
Modern UX, UI, and front-end tools
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuning
 
Coding standards php
Coding standards phpCoding standards php
Coding standards php
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
Coding Best practices (PHP)
Coding Best practices (PHP)Coding Best practices (PHP)
Coding Best practices (PHP)
 
Modular & Event driven UI Architecture
Modular & Event driven UI ArchitectureModular & Event driven UI Architecture
Modular & Event driven UI Architecture
 
PHP CODING STANDARDS
PHP CODING STANDARDSPHP CODING STANDARDS
PHP CODING STANDARDS
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
 
Modern Static Code Analysis in PHP
Modern Static Code Analysis in PHPModern Static Code Analysis in PHP
Modern Static Code Analysis in PHP
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
Component Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanComponent Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex Moldovan
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelines
 
UI Architecture & Web Performance
UI Architecture & Web PerformanceUI Architecture & Web Performance
UI Architecture & Web Performance
 
Selenium Architecture
Selenium ArchitectureSelenium Architecture
Selenium Architecture
 

Ähnlich wie JavaScript and UI Architecture Best Practices

Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 

Ähnlich wie JavaScript and UI Architecture Best Practices (20)

Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Formatting ForThe Masses
Formatting ForThe MassesFormatting ForThe Masses
Formatting ForThe Masses
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit Testing
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 

Kürzlich hochgeladen

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
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.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...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 

JavaScript and UI Architecture Best Practices

  • 1.
  • 2. JavaScript and UI Architecture Best Practices Siarhei Barysiuk s.barysiuk@sam-solutions.net
  • 4. Introduction: What will we cover today? • Coding patterns JavaScript-specific best practices • Design patterns Language independent patterns, UI architecture
  • 7. Tip of the day “Global variables should be avoided in order to lower the possibility of variable naming collisions. “
  • 8. Namespaces: Defining namespace //defining top-level package var MyApp = MyApp || {}; //defining package //defining package MyApp.dom = { MyApp.string = MyApp.string || {}; addEventListener: function(element, //defining package callback) { MyApp.string.utils = { //code goes here trim: function(str) { }, //code goes here removeEventListener: function(element, }, callback) { reverse: function(str) { //code goes here //code goes here } } }; };
  • 9. Namespaces: Usage in code MyApp.string.utils.reverse(...); MyApp.string.utils.trim(...); MyApp.dom.addEventListener(...); MyApp.dom.removeEventListener(...);
  • 10. Namespaces: namespace() function //defining top-level package var MyApp = MyApp || {}; //defines package structure MyApp.namespace = function(name) { if(name) { //some checks if name is valid var names = name.split(quot;.quot;); var current = MyApp; for(var i in names) { if(!current[names[i]]) { current[names[i]] = {}; } current = current[names[i]]; } return true; } return false; };
  • 11. Namespaces: Defining namespace //defining top-level package var MyApp = MyApp || {}; //defining package //defining package MyApp.string = MyApp.string || {}; MyApp.namespace(quot;string.utilsquot;); //defining package //defining package MyApp.string.utils = { MyApp.string.utils.trim = function(str) { trim: function(str) { //code goes here //code goes here console.log(quot;trimquot;); }, }; reverse: function(str) { //code goes here MyApp.string.utils.reverse = function(str) { } //code goes here }; console.log(quot;reversequot;); };
  • 14. Tip of the day “Branch some parts of the browser-specific code during initialization, when the script loads, rather than during runtime to avoid performance hit.”
  • 15. Init-time branching: Defining browser-specific methods MyApp.namespace(quot;domquot;); MyApp.dom.addListener = null; //all major browsers if(typeof window.addEventListener === 'function') { MyApp.dom.addListener = function(el, type, fn) { el.addEventListener(type, fn, false); }; } //IE else if(typeof document.attachEvent === 'function') { MyApp.dom.addListener = function(el, type, fn) { el.attachEvent('on' + type, fn); }; } //older browsers else { MyApp.dom.addListener = function(el, type, fn) { el['on' + type] = fn; }; }
  • 18. Tip of the day “The lazy definition pattern is very similar to the previous init-time branching pattern. The difference is that the branching happens only when the function is called for the first time.”
  • 19. Lazy definition: Defining browser-specific methods var MyApp = MyApp || {}; Override function first time MyApp.dom = { addListener: function(el, type, fn){ if (typeof el.addEventListener === 'function') { MyApp.dom.addListener = function(el, type, fn) { el.addEventListener(type, fn, false); }; } else if (typeof el.attachEvent === 'function'){ MyApp.dom.addListener = function(el, type, fn) { el.attachEvent('on' + type, fn); }; } else { MyApp.dom.addListener = function(el, type, fn) { el['on' + type] = fn; }; } MyApp.dom.addListener(el, type, fn); } };
  • 22. Tip of the day “Instead of having many parameters, you can use one parameter and make it an object. The properties of the object are the actual parameters.”
  • 23. Configuration object: Ordinary constructor var MyApp = MyApp || {}; MyApp.namespace(quot;domquot;); MyApp.dom.Button = function(text, type) { //some code here } MyApp.dom.Button = function(text, type, color, border, font) { //some code here }
  • 24. Configuration object: Usage of configuration object var MyApp = MyApp || {}; MyApp.namespace(quot;domquot;); MyApp.dom.Button = function(text, settings) { var type = settings.type || 'submit'; var font =settings.font ||'Verdana'; //..other props //some code here }
  • 27. Tip of the day “Use local variables and methods inside a constructor to achieve the “private” level of protection. Use naming conventions _doInternalOperation to show that the function is private/protected.”
  • 28. Private methods and properties: Private method var MyApp = MyApp || {}; MyApp.namespace(quot;domquot;); MyApp.dom.Button = function(text, settings) { //..process properties function setStyle(element, settings) { //setting style to element }; var button = //... //.. setStyle(button,settings); this.clone = function() { var clonedButton = //... //... setStyle(clonedButton, settings); } //some code here }
  • 31. Tip of the day “Self-executing functions are especially suitable for one-off initialization tasks performed when the script loads.”
  • 32. Self-executing functions: Usage (function() { //code goes here })(); (function(){ // ... var jQuery = window.jQuery = window.$ = function( selector, context ) { // ... return new jQuery.fn.init( selector, context ); }; // ... jQuery.fn = jQuery.prototype = { init: function() { //... } }; })();
  • 35. Tip of the day “Pretty convenient way to call several related methods on one line as if the methods are the links in a chain.”
  • 36. Chaining: Usage var obj = new MyApp.dom.Element('span'); var obj = new MyApp.dom.Element('span'); obj.setText('hello'); obj.setText('hello') obj.setStyle('color', 'red'); .setStyle('color', 'red') obj.setStyle('font', 'Verdana'); .setStyle('font', 'Verdana'); document.body.appendChild(obj); document.body.appendChild(obj); document.body.appendChild( new MyApp.dom.Element('span') .setText('hello') .setStyle('color', 'red') .setStyle('font', 'Verdana') );
  • 40. Unobtrusive JavaScript: Separate JavaScript functionality <a onclick=quot;doSomething()quot; href=quot;#quot;>Click!</a> <a href=quot;backuplink.htmlquot; class=quot;doSomethingquot;>Click!</a> $('a.doSomething').click(function(){ // Do something here! alert('You did something, woo hoo!'); });
  • 41. Unobtrusive JavaScript: Never depend on JavaScript <script type=quot;text/javascriptquot;> var now = new Date(); if(now.getHours() < 12) document.write('Good Morning!'); else document.write('Good Afternoon!'); </script> <p title=quot;Good Day Messagequot;>Good Morning!</p> var now = new Date(); if(now.getHours() >= 12) { var goodDay = $('p[title=quot;Good Day Messagequot;]'); goodDay.text('Good Afternoon!'); }
  • 42. Unobtrusive JavaScript: Never depend on JavaScript <a href=quot;javascript:window.open('page.html')quot;>my page</a> <a href=quot;#quot; onclick=quot;window.open('page.html')quot;>my page</a> <a href=quot;page.htmlquot; onclick=quot;window.open(this.href)quot;>my page</a> <a href=quot;page.htmlquot; class=quot;popupquot;>my page</a> //some java script to open element with class quot;.popupquot; in a new window