Upload
hernan-mammana
View
209
Download
0
Embed Size (px)
DESCRIPTION
Talk given at MercadoLibre, as a first idea, about how to organise your JavaScript code.
Citation preview
JavaScript Coding & Design Patterns
ContentGetting Started
JavaScript Style Guide Namespace Dependencies’s Declaration
Dealing With Browsers Separation of Concerns Init-time Branching DOM Scripting Events
Design Patterns Singleton Module Pattern
Prototypal Inheritance The new keyword The Object.create method
Getting StartedJavaScript Style Guide, Namespace & Dependencies’s Declaration
JavaScript Style Guidehttps://github.com/mercadolibre/javascript-style-guide
NamespaceJavaScript doesn’t have built-in namespaces
Reduce globals variables
Avoid naming collisions
Avoid name prefixing
Namespacevar fleet = fleet || {};
Dependencies’s DeclarationExplicit declaration the modules at the top
Easy to find and resolve dependencies
Working with local is faster than working with global
Smaller code when minifies the module for production
Dependencies’s Declarationfunction Car() { var Motor = vehicle.Motor, Wheel = vehicle.Wheel; }
Dealing with BrowsersSeparation of Concerns, Init-time Branching, DOM Scripting & Events
Separation of ConcernsImproves the delivery to a vast array of user agents
Enhance the site progressively
Test it without CSS
Test it without JS
Init-time BranchingOptimization pattern to test a condition only once
Common used on browser feature detection
Init-time Branchingvar w = window,
modern = w.addEventListener !== undefined,
on = modern ? ‘addEventListener’ : ‘attachEvent’,
click = modern ? ‘click’ : ‘onclick’; !
document.body[on](click, function(){});
DOM ScriptingInconsistently implemented across browsers
Avoiding DOM access in loops
Assigning DOM reference to local variables
Use selector APIs methods
Caching the length when iteration over a HTML collection
Change the DOM outside the live document
DOM Scriptingvar collection = document.querySelectorAll('.cars'), collectionLength = collection.length, item = 0; function addWheel(){ for (item; item < collectionLength; item ++) { var car = collection[item]; car.setAttribute('data-item-number', item); car.setAttribute('data-item-message', message[item]); }
}
EventsAttaching listeners unobtrusively helps reutilisation
Delegates event helps performance
Event Delegationvar container = document.querySelector(‘.parking’), child; !
container.addEventListener(‘click’, function(ev){ if(ev.target.hasAttribute(‘data-car’)){ child = ev.target; child.setAttribute(‘selected’, ‘selected’); } });
FunctionsScope, Hoisting, Configuration Object, IIFE
FunctionsThey have a variety of tasks, other languages may have special syntax for it
They are first-class objects
They provide scope
Can have their own properties and methods
Can be passed as argument and returned by other functions
Can be augmented, assigned to variables, referenced and deleted
ScopeJavaScript has not special syntax to denote private, protected or public properties or methods
JavaScript is a function scope language
Scopevar code = 93854782; !
function Car(){ var code; }
HoistingJavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function.
Hoistingfunction Car(){
var code, motor, wheels, doors; !
}
Configuration ObjectCar({ 'code': 'A195', 'wheels': 4, 'doors': 3, 'color': 'blue' });
Immediately-Invoked Function ExpressionIt is a syntax that enables you to execute a function as soon as it is defined
It provides a scope sandbox for your initialisation code
It can receive arguments
It can return values
It can be used when define object properties
It helps doing work wrapped without leaving any global variable
IIFE Immediately-Invoked Function Expression
(function(){ /* code */
}());
Design PatternsSingleton, Module Pattern
SingletonOnly one instance of a specific class
A simple way is creating a object literal
Every time you use the object literal syntax you are creating a singleton
It is possible to use the new keyword to create a singleton
Singleton simple wayvar parking = {};
Singleton with the new keywordfunction Parking(){ if(typeof Parking.instance === 'object') { return Parking.instance; } Parking.instance = this; return this; }
Module PatternIt provides structure and helps organise your code as it grows It provides the tools to create self-container decoupled pieces of code It is a combination of the following patterns
Namespaces Immediate functions Private and privileged members Declaring dependencies
Module Patternvar parking = (function () { var _places = [], // private module = {}; // public !
module.isTaken = function(placeNumber){}; !
return module; }());
Module Pattern(function(exports) { var _places = [], module = {}; // public !
module.isTaken = function(placeNumber){}; !
exports.module; }(parking));
Prototypal InheritanceThe new keyword & The Object.create() method
Prototypal InheritanceJavaScript is classified as having a prototype-based object model.
It is simple, a new object can inherit the properties of an old object.
Every function has a prototype property and it contains an object.
Add functionality by adding methods and properties to the prototype.
The new keywordfunction Car(brand, doors){ this.brand = brand; this.doors = doors; return this; } !
Car.prototype.run = function(){} !
var peugeot = new Car(‘peugeot’, 4);
The Object.create() methodvar Car = { ‘run’: function(){}, ‘init’: function(brand, doors){ this.brand = brand; this.doors = doors; } } !
var peugeot = Objetc.create(Car);