Top Banner
Architecting JavaScript Code Suresh Balla Principal Consultant Neudesic
27

Architecting JavaScript Code

Nov 12, 2014

Download

Spiritual

Suresh Balla

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Architecting JavaScript Code

Architecting JavaScript Code

Suresh BallaPrincipal ConsultantNeudesic

Page 2: Architecting JavaScript Code

Why do we need JavaScript patterns• Function Spaghetti Code• Closures to the Rescue

• Patterns• Prototype, Module

• Architecting Large JavaScript Codebases• Require.JS

Agenda

Page 3: Architecting JavaScript Code

Why do we need JavaScript patterns?

Page 4: Architecting JavaScript Code

Function Spaghetti Code

Page 5: Architecting JavaScript Code

Problems with Function Spaghetti Code• Variables/functions added into global scope• Potential for duplicate function names• Not modular• Not easy to maintain• No sense of a “container”

Page 6: Architecting JavaScript Code

Closures to the Rescue

Page 7: Architecting JavaScript Code

What is a Closure?

“…an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.”

~ Douglas Crockford

Page 8: Architecting JavaScript Code

Non-Closure Example

function myNonClosure() { var date = new Date(); return date.getMilliseconds();

}

Variable lost after function returns

Page 9: Architecting JavaScript Code

Closure Example

function myClosure() { var date = new Date();

//nested function return function () {

return date.getMilliseconds(); };

}

Variable stays around even after function returns

Page 10: Architecting JavaScript Code

Prototype Pattern

Page 11: Architecting JavaScript Code

The Prototype Pattern• Pros: • Leverage JavaScript’s built-in features • “Modularize” code into re-useable objects • Variables/functions taken out of global namespace • Functions loaded into memory once • Possible to “override” functions through prototyping

• Cons: • “this” can be tricky • Constructor separate from prototype definition

Page 12: Architecting JavaScript Code

Prototype Pattern Structure

var Calculator = function(eq) {this.eqCtl = document.getElementById(eq);

};

Calculator.prototype = {add: function (x, y) {

var val = x + y;this.eqCtl.innerHTML = val;

}}

var calc = new Calculator('eqCtl');calc.add(2,2)

Page 13: Architecting JavaScript Code

Prototype Pattern Demo

Page 14: Architecting JavaScript Code

The Module Pattern

Page 15: Architecting JavaScript Code

The Module Pattern• Pros: • “Modularize” code into re-useable objects • Variables/functions taken out of global namespace • Expose only public members while hiding private

members

• Cons: • Functions may be duplicated across objects in memory

when not using singleton • Not easy to extend

Page 16: Architecting JavaScript Code

Module Structure Overview

var Calculator = function() {//private variables //private functions

return {//public members

};};

Page 17: Architecting JavaScript Code

Module Pattern Structure var Calculator = function(eq) {

//private membervar eqCtl = document.getElementById(eq);

return { //expose public member add: function(x,y) {

var val = x + y;eqCtl.innerHTML = val; }

};};

var calculator = new Calculator('eq');calculator.add(2,2)

Page 18: Architecting JavaScript Code

Module Pattern Structure Demo

Page 19: Architecting JavaScript Code

Architecting Large JavaScript Codebases• In C#, Assembly is Package

• JavaScript Feels Like File Based• Two Real Options• Build for Coexistence• Require.js

Page 20: Architecting JavaScript Code

Architecting Large JavaScript CodebasesIsolating Scripts with Namespaces

<html> ...

<script source="first.js"></script> <script source="second.js"></script>

</html>

// first.js (function(ns) {

ns.Customer = function() { this.name = "";

}; }(window.WilderMinds = window.WilderMinds || {}));

// second.js (function(ns) {

ns.Order = function() { ... }; }(window.WilderMinds = window.WilderMinds || {}));

Page 21: Architecting JavaScript Code

Architecting Large JavaScript Codebases • Require.js • http://requirejs.org/ • Uses the Asynchronous Module Definition (AMD) pattern • Dependency Injection for JavaScript • Loads Scripts as they are needed instead of all at start

Page 22: Architecting JavaScript Code

Architecting Large JavaScript Codebases• Require.js • Include the Script • Add attribute for the startup script

<!DOCTYPE html> <html lang="en"> <head>

<meta charset="utf-8"> <title>RequireJS</title>

</head><body>

<script src="scripts/require.js" data-main="scripts/lib/main.js"> </script> </body></html>

Page 23: Architecting JavaScript Code

Architecting Large JavaScript Codebases• Require.js• Main Script is executed on startup

// main.js require(["Customer"],

// Requires the Customer Module function (Customer) { // Call with required

Module(s) // Your Initialization Code var c = new Customer("A Customer"); var name = c.name;

} );

Page 24: Architecting JavaScript Code

Architecting Large JavaScript Codebases• Require.js• Module Defined in similar way with define()

// Customer.js define( [], // Required Scripts (None)

function(){ // Gets any required modules here like main function Customer (name) {

this.name = name } return Customer; // Return the object that

Requires //constructor to allow you to call it }

Page 25: Architecting JavaScript Code

Require.JS Demo

Page 26: Architecting JavaScript Code

Q&A