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

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
 

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

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

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

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 En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
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

Recently uploaded (20)

A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 

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