SlideShare a Scribd company logo
Building Large Scale
Javascript Application
It's a little different than traditional JS
Who are the target audience?
What is Javascript?
I use JS to do form validation
Javascript is the interactive tool that I use for user intraction
I write the full app in JS
What do we actually mean by Large Scale Javascript
Application?
Large in size?
Large in complexity?
Large in developer count?
Why do we care?
The ability of browsers have increased
The load on the client, rather than on the server
High level of interaction
What is the secret of building BIG things?
Aircrafts are amazing architecture!
How they made this crazy huge thing?
The secret to building large apps is never build large
apps. Break up your applications into small pieces.
Then, assemble those testable, bite-sized pieces into
your big
– Justin Meyer
Okay, Let's start
As we generally start
We have a good main.js
function somethingGood() {
    // Good code
}
// few other functions ...
$( document ).ready(function() {
    $('#aButton').onClick(function(e) {
        // Do something
    });
    // few event bindings ...
});
        
But at the end, it become bad!
function somethingGood() {
    // ## Bad code, full of mess ##
}
// 39 strange functions with 40% repetation
$( document ).ready(function() {
    $('#aButton').onClick(function(e) {
        // Do something ## became 60 lines! ##
    });
    // ## 33 bindings ## , some event may bound multiple times
});
        
Let's break them down
Files++
Filesize--
Lots of files...
Let’s Organise them
By feature By Layer
By feature By Layer
Lets call them Modules
Okay, but...
What is a Module?
My Yahoo!
Modules made it!
Modules are (preferably) small, focused, purposeful
portion of code that -
Modules ... portion of code that -
Provides a specific feature
Modules ... portion of code that -
Contains business logic
Modules ... portion of code that -
Is decoupled (from other modules)
Modules ... portion of code that -
Is reusable (context matters)
Modules ... portion of code that -
Is testable
A simple module looks like -
var MyModule = ( function( window, $ ) {
  function aPrivateMethod() {
    $('catchSomething').load('http://...');
  }
  function myPublicMethod() {
    privateMethod();
    alert( 'my other method' );
  }
  // explicitly return public methods when this object is instantiated
  return {
    someMethod : myPublicMethod
  };
} )( window, jQuery );
        
Module rules
Module Rule #1
Never access the DOM outside the module
Building Large Scale Javascript Application
Module Rule #2
Don't Create Global variables
Module Rule #3
Don’t Access Non-Native, Global objects
Module Rule #4
Inject Dependencies
Module Communation
with other modules
Building Large Scale Javascript Application
Building Large Scale Javascript Application
Mediator Pattern
Mediators are used when the communication between modules may be complex, but is still
well defined.
Mediators and Modules
Mediator publish/subscribe example
// example subscriber function
var Subscriber = function ExampleSubscriber( myVariable ) {
  console.log( myVariable );
};
// example usages
var myMediator = new Mediator();
myMediator.subscribe( 'some event', Subscriber );
myMediator.publish( 'some event', 'foo bar' ); // console logs "foo bar"
        
Building Large Scale Javascript Application
Well defined Interfacing
Dependencies
Dependency on other code/Globals
Dependency on other files
Dependency on third party libraries
$('#my‐button').click(function() {
    $.get('https://api.github.com', function(data) {
        $('#res').html(data.emojis_url);
    });
});
        
Closure cannot be reused
Closure cannot be tested
$.get and $('#res') using global object
var downloadEmojis = function() {
    $.get('https://api.github.com', function(data) {
        $('#res').html(data.emojis_url);
    });
};
$('#my‐button').click(downloadEmojis);
        
Difficult to test
$.get and $('#res') using global object
var downloadEmojis = function(ajax, $el) {
    ajax.get('https://api.github.com', function(data) {
        $el.html(data.emojis_url);
    });
};
$('#my‐button').click(function() {
    downloadEmojis($, $('#res'));
});
        
Now we can controle dependencies :)
Dependency on other files/Modules
Scripts behind this presentation
<script src="bower_components/bespoke.js/dist/bespoke.min.js"></script>
<script src="bower_components/bespoke‐keys/dist/bespoke‐keys.min.js"></script>
<script src="bower_components/bespoke‐touch/dist/bespoke‐touch.min.js"></script>
<script src="bower_components/bespoke‐bullets/dist/bespoke‐bullets.min.js"></script>
<script src="bower_components/bespoke‐scale/dist/bespoke‐scale.min.js"></script>
<script src="bower_components/bespoke‐hash/dist/bespoke‐hash.min.js"></script>
<script src="bower_components/bespoke‐progress/dist/bespoke‐progress.min.js"></script>
<script src="bower_components/bespoke‐state/dist/bespoke‐state.min.js"></script>
<script src="bower_components/prism/prism.js"></script>
<script src="bower_components/prism/components/prism‐php.min.js"></script>
<script src="scripts/main.js"></script>
    
How can we make it better?
AMD
COMMON.JS
Let's see a little bit more about AMD
Using require.js
Using require.js
Include Require JS
<script data‐main="scripts/main" src="scripts/require.js"></script>
Using require.js
Configure Paths
require.config({
    baseUrl: 'js/lib',
    paths: {
        jquery: 'jquery‐1.9.0'
        parse : 'parse‐1.2.18.min',
        underscore: 'underscore',
        backbone: 'backbone',
        marionette: 'backbone.marionette'
    }
});
Using require.js
Define modules
define([
    'app',
    'marionette'
], function(app, Marionette){
    return ExampleModule = app.module("Example", function(Example) {
        this.startWithParent = false;
        this.addInitializer(function(){
            console.log('Module:Example => initialized');
            this.router = new Router({ controller: Controller });
        });
    });
});
Asynchronous loading
On demand script loading
 if(teamProfile) {
    // Load and show team profile
    require(['views/TeamProfileView'], function(TeamProfileView) {
        var teamInfo = { model : app.reqres.request('core:team', shortName) }
        app.main.show(new TeamProfileView(teamInfo));
    });
}
            
Dependency on third party libraries
http://bower.io/
list dependencies in bower.json
// bower.json
{
    "dependencies": {
        "angular": "~1.0.7",
        "angular‐resource": "~1.0.7",
        "jquery": "1.9.1"
} }
MV* Frameworks
Seperation between Data and DOM
M → Data | V → DOM | * → has many variations
MVC
Controller → Mediates inputs and manipulates the model
MVP
Presenter → all presentation logic is pushed to the presenter
MVVM
ViewModel → exposes model so it can be easily managed and consumed
How to select the right one?
Why they are this huge in nymbers? :(
Same todo app built around 70 times with different frameworks and approaches
Building Large Scale Javascript Application
Let's see how BackboneJS did it
Todo Model
(function () {
    app.Todo = Backbone.Model.extend({
        // and ensure that each todo created has `title` and `completed` keys.
        defaults: {
            title: '',
            completed: false
        },
        toggle: function () {
            this.save({
                completed: !this.get('completed')
            });
        }
    });
})();
Create a Todo
var todo = new app.Todo({
  title: "Do something good!"
});
What about list of Todos?
var Todos = Backbone.Collection.extend({
        model: app.Todo,
        // Filter down the list of all todo items that are finished.
        completed: function () {
            return this.filter(function (todo) {
                return todo.get('completed');
            });
        },
        // Many other functions related to list ...
    });
Collections
Create a Todo list
var todoList = new Todos(
    {title: 'Do something good'},
    {title: 'Another Task'},
    {title: 'This task is Done', completed: true},
);
            
Who will create them actually?
collection.fetch(); // Pulls list of items from server
collection.create(); // Create new item in list
// Sync a model
model.fetch(); // Fetch an item from server
model.save(); // Save changes to model
model.destroy(); // Delete a model
            
Template
<script type="text/template" id="item‐template">
    <div class="view">
        <input class="toggle" type="checkbox" <%= completed ? 'checked' : '' %>>
        <label><%= title %></label>
        <button class="destroy"></button>
    </div>
    <input class="edit" value="<%‐ title %>">
</script>
            
The DOM to render models or collection
Views
app.TodoView = Backbone.View.extend({
    tagName:  'li',
    template: _.template($('#item‐template').html()),
    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'visible', this.toggleVisible);
    },
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});
            
Takes models, Render them, listning to events
Views cont.
events: {
    'click .toggle': 'toggleCompleted',
    'dblclick label': 'edit'
},
toggleCompleted: function () {
    this.model.toggle();
},
edit: function () {
    this.$el.addClass('editing');
    this.$input.focus();
},
        
Handling to DOM events and manipulate model
Routers
var TodoRouter = Backbone.Router.extend({
        routes: {
            '*filter': 'setFilter',
            'url/pattern': 'handlerFunction'
            'url/pattern/:param': 'handlerFunction'
        },
        setFilter: function (param) {
            // Trigger a collection filter event
            app.todos.trigger('filter');
        }
    });
        
Handles the routing with url changes
Start listning to url changes
app.TodoRouter = new TodoRouter();
Backbone.history.start();
    
Url change? reload?... NO
http://the/app/url.com#a‐route
http://the/app/url.com#another‐route
http://the/app/url.com#a‐route/withParam/23
    
No more today
It was a lot of things... ain't it?
Wait... Do I really need aaall of these?
Well, depends on your apps requirement
Resource
http://superherojs.com/
About us
[
    {
        "name": "Mohammad Emran Hasan",
        "mail": "phpfour@gmail.com",
        "blog": "http://emranhasan.com"
    },
    {
        "name": "Anis Uddin Ahmad",
        "mail": "anisniit@gmail.com",
        "blog": "http://ajaxray.com"
    }
]
          
Questions?

More Related Content

PPT
закон кулона
PPT
Релігія та церква (7 кл.- вс.історія)
PPTX
аналіз ринку фінансових інвестицій
PPTX
The Many Ways to Build Modular JavaScript
PDF
Javascript Module Patterns
PPTX
MVVM Design Pattern NDC2009
PPTX
Mean stack Magics
KEY
Mobile optimization
закон кулона
Релігія та церква (7 кл.- вс.історія)
аналіз ринку фінансових інвестицій
The Many Ways to Build Modular JavaScript
Javascript Module Patterns
MVVM Design Pattern NDC2009
Mean stack Magics
Mobile optimization

Similar to Building Large Scale Javascript Application (20)

PPTX
Built to last javascript for enterprise
PPTX
React js - The Core Concepts
PPTX
jquery summit presentation for large scale javascript applications
PDF
Testing Big in JavaScript
PDF
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
PDF
A gently introduction to AngularJS
PPTX
Fundaments of Knockout js
DOCX
A report on mvc using the information
PPT
Building Rich User Experiences Without JavaScript Spaghetti
PPTX
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
PDF
Fewd week4 slides
PDF
Designing and Implementing a Multiuser Apps Platform
PDF
MVC pattern for widgets
PDF
Developing large scale JavaScript applications
PDF
Александр Белецкий "Архитектура Javascript приложений"
PPTX
Xam expertday
PDF
From Legacy to Hexagonal (An Unexpected Android Journey)
PDF
Angular js meetup
PPTX
Writing modular java script
PDF
jQuery Interview Questions By ScholarHat.pdf
Built to last javascript for enterprise
React js - The Core Concepts
jquery summit presentation for large scale javascript applications
Testing Big in JavaScript
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
A gently introduction to AngularJS
Fundaments of Knockout js
A report on mvc using the information
Building Rich User Experiences Without JavaScript Spaghetti
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Fewd week4 slides
Designing and Implementing a Multiuser Apps Platform
MVC pattern for widgets
Developing large scale JavaScript applications
Александр Белецкий "Архитектура Javascript приложений"
Xam expertday
From Legacy to Hexagonal (An Unexpected Android Journey)
Angular js meetup
Writing modular java script
jQuery Interview Questions By ScholarHat.pdf
Ad

More from Anis Ahmad (8)

PDF
Testing in Laravel Framework
PDF
Writing Sensible Code
PDF
Revisiting SOLID Principles
PDF
VCS for Teamwork - GIT Workshop
PDF
Developing cross platform desktop application with Ruby
PDF
Caching basics in PHP
PDF
Freelancing; an alternate career
PPTX
jQuery from the very beginning
Testing in Laravel Framework
Writing Sensible Code
Revisiting SOLID Principles
VCS for Teamwork - GIT Workshop
Developing cross platform desktop application with Ruby
Caching basics in PHP
Freelancing; an alternate career
jQuery from the very beginning
Ad

Recently uploaded (20)

PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
AI in Product Development-omnex systems
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Introduction to Artificial Intelligence
PPTX
ai tools demonstartion for schools and inter college
PDF
Odoo Companies in India – Driving Business Transformation.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
AI in Product Development-omnex systems
How to Choose the Right IT Partner for Your Business in Malaysia
Which alternative to Crystal Reports is best for small or large businesses.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How Creative Agencies Leverage Project Management Software.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
ISO 45001 Occupational Health and Safety Management System
How to Migrate SBCGlobal Email to Yahoo Easily
Online Work Permit System for Fast Permit Processing
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Introduction to Artificial Intelligence
ai tools demonstartion for schools and inter college
Odoo Companies in India – Driving Business Transformation.pdf

Building Large Scale Javascript Application