SlideShare a Scribd company logo
1 of 43
Download to read offline
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?

More Related Content

What's hot

Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSVisual Engineering
 
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 JasminePaulo Ragonha
 
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 WebpackIgnacio Martín
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practicesChengHui Weng
 
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!Eric Palakovich Carr
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019julien pauli
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
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...Domenic Denicola
 
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 KarmaExoLeaders.com
 

What's hot (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
 

Viewers also liked

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 DevelopmentSuresh Patidar
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview QuestionsArc & Codementor
 
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 architectureshuchi tripathi
 
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 toolsAlan 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 tuningAndy Pemberton
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizenVytautas Butkus
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 
Coding Best practices (PHP)
Coding Best practices (PHP)Coding Best practices (PHP)
Coding Best practices (PHP)Christian Baune
 
Modular & Event driven UI Architecture
Modular & Event driven UI ArchitectureModular & Event driven UI Architecture
Modular & Event driven UI ArchitectureVytautas Butkus
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code ReviewMilan Vukoje
 
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...Rouven Weßling
 
Modern Static Code Analysis in PHP
Modern Static Code Analysis in PHPModern Static Code Analysis in PHP
Modern Static Code Analysis in PHPVladimir Reznichenko
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 
Component Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanComponent Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanITCamp
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelinesLalit Kale
 
UI Architecture & Web Performance
UI Architecture & Web PerformanceUI Architecture & Web Performance
UI Architecture & Web PerformanceKyle Simpson
 
Selenium Architecture
Selenium ArchitectureSelenium Architecture
Selenium Architecturerohitnayak
 

Viewers also liked (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
 

Similar to JavaScript and UI Architecture Best Practices

Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
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 SupportBen Scofield
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Davide Cerbo
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming Enguest9bcef2f
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
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 FrameworkBen Scofield
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
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.Alberto Naranjo
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
Formatting ForThe Masses
Formatting ForThe MassesFormatting ForThe Masses
Formatting ForThe MassesHolger Schill
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of PluginYasuo Harada
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit TestingBenjamin Wilson
 
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 jsFrancois Zaninotto
 

Similar to 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
 

Recently uploaded

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...Orbitshub
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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.pdfOrbitshub
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
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 challengesrafiqahmad00786416
 
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)Zilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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
 
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, Adobeapidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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.pptxRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 

Recently uploaded (20)

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...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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 Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
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)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

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