SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler 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?

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a JavaScript 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
 

Semelhante a JavaScript 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
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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 WorkerThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

JavaScript 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