SlideShare a Scribd company logo
Gran Sasso Science Institute
Ivano Malavolta
Handlebars
& Require JS
Roadmap
•  Introduction
•  Require JS
•  Handlebars
•  Conclusions
Some technical advices from a real project...
Some technical advices from a real project...
Some technical advices from a real project...
Some technical advices from a real project...
Some technical advices from a real project...
How you structure your applications
MVC framework for
giving structure
File and module loader
for code modularization
Templating engine for
separation of concerns
How you structure your applications
Roadmap
•  Introduction
•  Require JS
•  Handlebars
•  Conclusions
Require JS
•  Why Require JS
•  Using modules
•  Defining modules
•  Configuring Require JS
Why Require JS
We are building apps, not websites
We need well-specified and isolated JS files/modules
Code complexity grows as the app gets bigger
à we need some sort of #include/import/require	
  
à ability to load nested dependencies
What we want to avoid
uncontrolled scripts
poor control flow understanding
RequireJS
RequireJS is a JavaScript file and module loader
Using a modular script loader like RequireJS will improve the modularity of your code
à  speed in implementing changes
à  better undestanding of the code
Require JS allows modules to be loaded as fast as possible, even out of order, but evaluated in the
correct dependency order
Built on the Module Pattern
JavaScript file and module loader
The module pattern
A JavaScript code module is some JavaScript code located in a registered location (e.g., a function)
All of the code that runs inside the function lives in a closure, which provides
•  privacy
•  state
throughout the lifetime of the module
Module example
Technically, it is simply a function that executes immediately
Module VS script files
A module is different from a traditional script file in that it defines a well-scoped object that avoids
polluting the global namespace à its retained objects can be deleted by the GC
It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to
global objects, but instead receive the dependencies as arguments to the function that defines the
module
VS
Require JS
•  Why Require JS
•  Using modules
•  Defining modules
•  Configuring Require JS
Using modules
main.js is the entry point of the app
The main HTML:
The main JS file:
Using modules
This function is called when all dependencies are loaded
If a required module calls define(), then this function is not
fired until its dependencies have been loaded
Required modules
References to
required modules
Require JS
•  Why Require JS
•  Using modules
•  Defining modules
•  Configuring Require JS
Module without dependencies Always one module per file
Public variables
Setup code
the simplest module can be a plain
collection of name/value pairs
module with initialization
The returned element can be any valid JS element
By convention I always return an object representing the
module
Module with dependencies
Dependency
definition
Dependent module reference
Dependent module
usage
This function is called when
zepto.js is loaded.
If zepto.js calls define(), then
this function is not fired until
also zepto’s dependencies
have loaded
Require JS under the hoods...
1.  loads each dependency as a script tag, using head.appendChild() and waits for all dependencies to
load
2.  computes the right order in which to call the functions that define the modules
3.  calls the module definition functions of each dependency in the right order
main.js
jQuery Backbone
SpinJS
MoviesCollection
MovieModel
MoviesView
1
2
3 4
5
67
Require JS
•  Why Require JS
•  Using modules
•  Defining modules
•  Configuring Require JS
Configuring Require JS
Require refers to a global configuration options
It allows developers to:
•  set the paths to all used frameworks in one place
•  use older frameworks as modules (shim)
•  define configuration params for the modules
•  etc.
Configuring Require JS
Shims for older
frameworks
paths to used frameworks
Dependent module
usage
Roadmap
•  Introduction
•  Require JS
•  Handlebars
•  Conclusions
Handlebars
•  Why Handlebars
•  Handlebars basics
•  Usage with Backbone and Require JS
Why Handlebars
We want to separate presentation from logic
TRANSLATE TO: we don’t want to put any HTML element into JavaScript code
separate logic from presentation
Imagine yourself trying to change how a movie should be rendered in
your app...
Handlebars
•  Why Handlebars
•  Handlebars basics
•  Usage with Backbone and Require JS
Example of template
A handlebars expression is
{{ something  }}
Escape values
Handlebars HTML-escapes all the values returned by an {{expression}}
If you don't want Handlebars to escape a value, use the "triple-stash“ à {{{ expression }}}
Populate your template
The recurrent process of obtaining a populated template is the following:
1.  create the template T with its placeholders {{ - }}
2.  compile the template into a JavaScript function t
3.  create a context CT containing the actual values for placeholders
4.  run the compiled template t(CT) to obtain the final HTML fragment
1. create the template
Templates are defined within a <script>	
  tag or in external files
2. compile the template
	
  
Handlebars.compile is used to compile a template
Compiling = obtaining a JS function representing the template
3. create a context for the template
	
  
A context is a JavaScript object used to populate a template
Here the keys of the object must match with the name of the placeholders to be populated
4. obtain the final HTML fragment
	
  
You have to execute a template with a context in order to get its corresponding HTML code
Expressions
	
  
The simplest expression is a simple identifier
This expression means "look up the username property in the current context"
Expressions with paths
Handlebars expressions can also be dot-separated paths
This expression means
"look up the user property in the current context,
then look up the username property of the user"
Helpers
Helpers are JavaScript functions that return HTML code
You should return a Handlebars SafeString if you don't want it to be escaped by default
Calling helpers
A Handlebars helper call is a simple identifier, followed by zero or more parameters
Each parameter is a Handlebars expression
es.
{{	
  test	
  user	
  }}	
  
In this case, test is the name of the Handlebars helper, and user is a parameter to the helper
Built-in helpers
It shifts the context for a section of a template
with
<div	
  class="entry“>	
  
<h1>{{title}}</h1>	
  
{{#with	
  author}}	
  
	
  <h2>By	
  {{firstName}}	
  {{lastName}}</h2>	
  
{{/with}}	
  
</div>	
  	
  
{	
  title:	
  "My	
  first	
  post!",	
  	
  
	
  	
  	
  author:	
  {	
  firstName:	
  “Ivano",	
  lastName:	
  “Malavolta"	
  }	
  
}	
  	
  
<div	
  class="entry“>	
  
<h1>My	
  first	
  post!</h1>	
  
<h2>By	
  Ivano	
  Malavolta</h2>	
  
</div>	
  	
  
Built-in helpers
To iterate over a list
each
Inside the block, you can use
this
to reference the element being iterated
<ul	
  class="people_list">	
  
	
   	
  {{#each	
  people}}	
  
	
   	
   	
  <li>{{this}}</li>	
  	
  
	
  {{/each}}	
  
	
  </ul>	
  	
  
{	
  people:	
  [	
  “Ivano",	
  “Andrea",	
  “Paolo"	
  ]	
  }	
  	
  
<ul	
  class="people_list">	
  	
  
	
  	
  <li>Ivano</li>	
  
	
  	
  <li>Andrea</li>	
  
	
  	
  <li>Paolo</li>	
  
</ul>	
  	
  
Built-in helpers
It renders the block if its argument is not equal to false,	
  undefined,	
  null,	
  []	
  
If / Else
The unless helper is the inverse of if
<div	
  class="entry“>	
  
<h1>{{title}}</h1>	
  
{{#if	
  author}}	
  
	
  <h2>By	
  {{firstName}}	
  {{lastName}}</h2>	
  
{{#else}}	
  
	
  <h2>Unknown	
  author</h1>	
  	
  
{{/if}}	
  
{	
  title:	
  "My	
  first	
  post!",	
  	
  
	
  	
  	
  author:	
  undefined	
  }	
  
}	
  	
  
<div	
  class="entry“>	
  
<h1>My	
  first	
  post!</h1>	
  
<h2>Unknown	
  author</h2>	
  
</div>	
  	
  
handlebars summary
Each Template can contain Expressions and Helpers operating on them
The main helpers are:
•  with	
  
•  each	
  
•  if	
  /	
  else	
  /unless	
  
You can define your own Helpers that operate on expressions, they return HTML code
A template can be (pre)-compiled and must be executed with a context in order to return the
final HTML fragment
Handlebars
•  Why Handlebars
•  Handlebars basics
•  Usage with Backbone and Require JS
Usage with Backbone and Require JS
Templates can be seen as special modules
So we can have the following:
•  a separate HTML file for each template
•  a Backbone view can have a dependency to each template
•  the template can be executed by using a JSON object of the Backbone model as context
Example
Dependency to template HTML file
It contains a string
Compiled template
Execution of the template
References
http://backbonejs.org
http://requirejs.org
http://handlebarsjs.com
https://github.com/iivanoo/cordovaboilerplate
Contact
Ivano Malavolta |
Gran Sasso Science Institute
iivanoo
ivano.malavolta@gssi.infn.it
www.ivanomalavolta.com

More Related Content

What's hot (20)

PDF
Fast mobile web apps
Ivano Malavolta
 
PDF
Backbone.js
Ivano Malavolta
 
PDF
Local storage in Web apps
Ivano Malavolta
 
PPTX
MVC & SQL_In_1_Hour
Dilip Patel
 
PDF
HTML5 and CSS3 refresher
Ivano Malavolta
 
PPTX
Getting Started with Angular JS
Akshay Mathur
 
PPTX
Asp.Net MVC 5 in Arabic
Haitham Shaddad
 
PDF
Great Responsive-ability Web Design
Mike Wilcox
 
PDF
D2W Branding Using jQuery ThemeRoller
WO Community
 
PDF
Apache Cordova 4.x
Ivano Malavolta
 
PDF
[2015/2016] The REST architectural style
Ivano Malavolta
 
PPTX
Angular js 1.3 basic tutorial
Al-Mutaz Bellah Salahat
 
PDF
Handlebars and Require.js
Ivano Malavolta
 
PDF
C# Advanced L09-HTML5+ASP
Mohammad Shaker
 
PDF
JavaScript
Ivano Malavolta
 
PPTX
Getting Started with jQuery
Akshay Mathur
 
PDF
MVC 1.0 als alternative Webtechnologie
OPEN KNOWLEDGE GmbH
 
PPTX
Getting Started with Javascript
Akshay Mathur
 
PPTX
Angular js for Beginnners
Santosh Kumar Kar
 
Fast mobile web apps
Ivano Malavolta
 
Backbone.js
Ivano Malavolta
 
Local storage in Web apps
Ivano Malavolta
 
MVC & SQL_In_1_Hour
Dilip Patel
 
HTML5 and CSS3 refresher
Ivano Malavolta
 
Getting Started with Angular JS
Akshay Mathur
 
Asp.Net MVC 5 in Arabic
Haitham Shaddad
 
Great Responsive-ability Web Design
Mike Wilcox
 
D2W Branding Using jQuery ThemeRoller
WO Community
 
Apache Cordova 4.x
Ivano Malavolta
 
[2015/2016] The REST architectural style
Ivano Malavolta
 
Angular js 1.3 basic tutorial
Al-Mutaz Bellah Salahat
 
Handlebars and Require.js
Ivano Malavolta
 
C# Advanced L09-HTML5+ASP
Mohammad Shaker
 
JavaScript
Ivano Malavolta
 
Getting Started with jQuery
Akshay Mathur
 
MVC 1.0 als alternative Webtechnologie
OPEN KNOWLEDGE GmbH
 
Getting Started with Javascript
Akshay Mathur
 
Angular js for Beginnners
Santosh Kumar Kar
 

Viewers also liked (20)

PDF
Mobile geolocation and mapping
Ivano Malavolta
 
PDF
The Mobile ecosystem, Context & Strategies
Ivano Malavolta
 
PDF
Backbone.js
Ivano Malavolta
 
PDF
Mobile Apps Development: Technological strategies and Monetization
Ivano Malavolta
 
PDF
Apache Cordova APIs version 4.3.0
Ivano Malavolta
 
PDF
Local data storage for mobile apps
Ivano Malavolta
 
PDF
PhoneGap: Accessing Device Capabilities
Ivano Malavolta
 
PDF
UI Design Patterns for Mobile Apps
Ivano Malavolta
 
PDF
PhoneGap: Local Storage
Ivano Malavolta
 
PDF
Mobile Applications Development - Lecture 0 - Spring 2013
Ivano Malavolta
 
PDF
[2015/2016] Modern development paradigms
Ivano Malavolta
 
PDF
Mobile Applications Development - Lecture 0
Ivano Malavolta
 
PDF
Design patterns for mobile apps
Ivano Malavolta
 
PDF
UI design for mobile apps
Ivano Malavolta
 
PDF
PhoneGap
Ivano Malavolta
 
PDF
Sitemaps & Wireframing
Ivano Malavolta
 
PDF
Javascript and jQuery for Mobile
Ivano Malavolta
 
PDF
[2015/2016] Introduction to software architecture
Ivano Malavolta
 
PDF
[2015/2016] AADL (Architecture Analysis and Design Language)
Ivano Malavolta
 
PDF
[2015/2016] HTML5 and CSS3 Refresher
Ivano Malavolta
 
Mobile geolocation and mapping
Ivano Malavolta
 
The Mobile ecosystem, Context & Strategies
Ivano Malavolta
 
Backbone.js
Ivano Malavolta
 
Mobile Apps Development: Technological strategies and Monetization
Ivano Malavolta
 
Apache Cordova APIs version 4.3.0
Ivano Malavolta
 
Local data storage for mobile apps
Ivano Malavolta
 
PhoneGap: Accessing Device Capabilities
Ivano Malavolta
 
UI Design Patterns for Mobile Apps
Ivano Malavolta
 
PhoneGap: Local Storage
Ivano Malavolta
 
Mobile Applications Development - Lecture 0 - Spring 2013
Ivano Malavolta
 
[2015/2016] Modern development paradigms
Ivano Malavolta
 
Mobile Applications Development - Lecture 0
Ivano Malavolta
 
Design patterns for mobile apps
Ivano Malavolta
 
UI design for mobile apps
Ivano Malavolta
 
PhoneGap
Ivano Malavolta
 
Sitemaps & Wireframing
Ivano Malavolta
 
Javascript and jQuery for Mobile
Ivano Malavolta
 
[2015/2016] Introduction to software architecture
Ivano Malavolta
 
[2015/2016] AADL (Architecture Analysis and Design Language)
Ivano Malavolta
 
[2015/2016] HTML5 and CSS3 Refresher
Ivano Malavolta
 
Ad

Similar to Handlebars & Require JS (20)

PPTX
Mastering the Lightning Framework - Part 1
Salesforce Developers
 
PDF
Create an application with ember
Chandra Sekar
 
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
PPSX
RequireJS
Tim Doherty
 
PDF
Ionic framework one day training
Troy Miles
 
PPTX
Eclipse 40 and Eclipse e4
Lars Vogel
 
PPTX
Introduction to AngularJs
murtazahaveliwala
 
PPTX
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
PDF
Web component driven development
Gil Fink
 
PDF
Eclipse 40 - Eclipse Summit Europe 2010
Lars Vogel
 
PPT
Introduction to Zend Framework
Jamie Hurst
 
PPTX
Introduction to AngularJS
David Parsons
 
PDF
III - Better angularjs
WebF
 
PDF
End to-End SPA Development Using ASP.NET and AngularJS
Gil Fink
 
PPT
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 
PDF
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
Evan Mullins
 
PPTX
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
PPTX
Working with AngularJS
André Vala
 
PPT
Overview of PHP and MYSQL
Deblina Chowdhury
 
PDF
AEM Sightly Deep Dive
Gabriel Walt
 
Mastering the Lightning Framework - Part 1
Salesforce Developers
 
Create an application with ember
Chandra Sekar
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
RequireJS
Tim Doherty
 
Ionic framework one day training
Troy Miles
 
Eclipse 40 and Eclipse e4
Lars Vogel
 
Introduction to AngularJs
murtazahaveliwala
 
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
Web component driven development
Gil Fink
 
Eclipse 40 - Eclipse Summit Europe 2010
Lars Vogel
 
Introduction to Zend Framework
Jamie Hurst
 
Introduction to AngularJS
David Parsons
 
III - Better angularjs
WebF
 
End to-End SPA Development Using ASP.NET and AngularJS
Gil Fink
 
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
Evan Mullins
 
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
Working with AngularJS
André Vala
 
Overview of PHP and MYSQL
Deblina Chowdhury
 
AEM Sightly Deep Dive
Gabriel Walt
 
Ad

More from Ivano Malavolta (20)

PDF
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
PDF
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Ivano Malavolta
 
PDF
The H2020 experience
Ivano Malavolta
 
PDF
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
Ivano Malavolta
 
PDF
Software sustainability and Green IT
Ivano Malavolta
 
PDF
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Ivano Malavolta
 
PDF
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
Ivano Malavolta
 
PDF
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Ivano Malavolta
 
PDF
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Ivano Malavolta
 
PDF
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Ivano Malavolta
 
PDF
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Ivano Malavolta
 
PDF
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Ivano Malavolta
 
PDF
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Ivano Malavolta
 
PDF
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Ivano Malavolta
 
PDF
Modeling and abstraction, software development process [Software Design] [Com...
Ivano Malavolta
 
PDF
[2017/2018] Agile development
Ivano Malavolta
 
PDF
Reconstructing microservice-based architectures
Ivano Malavolta
 
PDF
[2017/2018] AADL - Architecture Analysis and Design Language
Ivano Malavolta
 
PDF
[2017/2018] Architectural languages
Ivano Malavolta
 
PDF
[2017/2018] Introduction to Software Architecture
Ivano Malavolta
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Ivano Malavolta
 
The H2020 experience
Ivano Malavolta
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
Ivano Malavolta
 
Software sustainability and Green IT
Ivano Malavolta
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Ivano Malavolta
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
Ivano Malavolta
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Ivano Malavolta
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Ivano Malavolta
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Ivano Malavolta
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Ivano Malavolta
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Ivano Malavolta
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Ivano Malavolta
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Ivano Malavolta
 
Modeling and abstraction, software development process [Software Design] [Com...
Ivano Malavolta
 
[2017/2018] Agile development
Ivano Malavolta
 
Reconstructing microservice-based architectures
Ivano Malavolta
 
[2017/2018] AADL - Architecture Analysis and Design Language
Ivano Malavolta
 
[2017/2018] Architectural languages
Ivano Malavolta
 
[2017/2018] Introduction to Software Architecture
Ivano Malavolta
 

Recently uploaded (20)

PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Handlebars & Require JS

  • 1. Gran Sasso Science Institute Ivano Malavolta Handlebars & Require JS
  • 2. Roadmap •  Introduction •  Require JS •  Handlebars •  Conclusions
  • 3. Some technical advices from a real project...
  • 4. Some technical advices from a real project...
  • 5. Some technical advices from a real project...
  • 6. Some technical advices from a real project...
  • 7. Some technical advices from a real project...
  • 8. How you structure your applications MVC framework for giving structure File and module loader for code modularization Templating engine for separation of concerns
  • 9. How you structure your applications
  • 10. Roadmap •  Introduction •  Require JS •  Handlebars •  Conclusions
  • 11. Require JS •  Why Require JS •  Using modules •  Defining modules •  Configuring Require JS
  • 12. Why Require JS We are building apps, not websites We need well-specified and isolated JS files/modules Code complexity grows as the app gets bigger à we need some sort of #include/import/require   à ability to load nested dependencies
  • 13. What we want to avoid uncontrolled scripts poor control flow understanding
  • 14. RequireJS RequireJS is a JavaScript file and module loader Using a modular script loader like RequireJS will improve the modularity of your code à  speed in implementing changes à  better undestanding of the code Require JS allows modules to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order Built on the Module Pattern JavaScript file and module loader
  • 15. The module pattern A JavaScript code module is some JavaScript code located in a registered location (e.g., a function) All of the code that runs inside the function lives in a closure, which provides •  privacy •  state throughout the lifetime of the module
  • 16. Module example Technically, it is simply a function that executes immediately
  • 17. Module VS script files A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace à its retained objects can be deleted by the GC It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module VS
  • 18. Require JS •  Why Require JS •  Using modules •  Defining modules •  Configuring Require JS
  • 19. Using modules main.js is the entry point of the app The main HTML:
  • 20. The main JS file: Using modules This function is called when all dependencies are loaded If a required module calls define(), then this function is not fired until its dependencies have been loaded Required modules References to required modules
  • 21. Require JS •  Why Require JS •  Using modules •  Defining modules •  Configuring Require JS
  • 22. Module without dependencies Always one module per file Public variables Setup code the simplest module can be a plain collection of name/value pairs module with initialization The returned element can be any valid JS element By convention I always return an object representing the module
  • 23. Module with dependencies Dependency definition Dependent module reference Dependent module usage This function is called when zepto.js is loaded. If zepto.js calls define(), then this function is not fired until also zepto’s dependencies have loaded
  • 24. Require JS under the hoods... 1.  loads each dependency as a script tag, using head.appendChild() and waits for all dependencies to load 2.  computes the right order in which to call the functions that define the modules 3.  calls the module definition functions of each dependency in the right order main.js jQuery Backbone SpinJS MoviesCollection MovieModel MoviesView 1 2 3 4 5 67
  • 25. Require JS •  Why Require JS •  Using modules •  Defining modules •  Configuring Require JS
  • 26. Configuring Require JS Require refers to a global configuration options It allows developers to: •  set the paths to all used frameworks in one place •  use older frameworks as modules (shim) •  define configuration params for the modules •  etc.
  • 27. Configuring Require JS Shims for older frameworks paths to used frameworks Dependent module usage
  • 28. Roadmap •  Introduction •  Require JS •  Handlebars •  Conclusions
  • 29. Handlebars •  Why Handlebars •  Handlebars basics •  Usage with Backbone and Require JS
  • 30. Why Handlebars We want to separate presentation from logic TRANSLATE TO: we don’t want to put any HTML element into JavaScript code separate logic from presentation Imagine yourself trying to change how a movie should be rendered in your app...
  • 31. Handlebars •  Why Handlebars •  Handlebars basics •  Usage with Backbone and Require JS
  • 32. Example of template A handlebars expression is {{ something  }}
  • 33. Escape values Handlebars HTML-escapes all the values returned by an {{expression}} If you don't want Handlebars to escape a value, use the "triple-stash“ à {{{ expression }}}
  • 34. Populate your template The recurrent process of obtaining a populated template is the following: 1.  create the template T with its placeholders {{ - }} 2.  compile the template into a JavaScript function t 3.  create a context CT containing the actual values for placeholders 4.  run the compiled template t(CT) to obtain the final HTML fragment
  • 35. 1. create the template Templates are defined within a <script>  tag or in external files
  • 36. 2. compile the template   Handlebars.compile is used to compile a template Compiling = obtaining a JS function representing the template
  • 37. 3. create a context for the template   A context is a JavaScript object used to populate a template Here the keys of the object must match with the name of the placeholders to be populated
  • 38. 4. obtain the final HTML fragment   You have to execute a template with a context in order to get its corresponding HTML code
  • 39. Expressions   The simplest expression is a simple identifier This expression means "look up the username property in the current context"
  • 40. Expressions with paths Handlebars expressions can also be dot-separated paths This expression means "look up the user property in the current context, then look up the username property of the user"
  • 41. Helpers Helpers are JavaScript functions that return HTML code You should return a Handlebars SafeString if you don't want it to be escaped by default
  • 42. Calling helpers A Handlebars helper call is a simple identifier, followed by zero or more parameters Each parameter is a Handlebars expression es. {{  test  user  }}   In this case, test is the name of the Handlebars helper, and user is a parameter to the helper
  • 43. Built-in helpers It shifts the context for a section of a template with <div  class="entry“>   <h1>{{title}}</h1>   {{#with  author}}    <h2>By  {{firstName}}  {{lastName}}</h2>   {{/with}}   </div>     {  title:  "My  first  post!",          author:  {  firstName:  “Ivano",  lastName:  “Malavolta"  }   }     <div  class="entry“>   <h1>My  first  post!</h1>   <h2>By  Ivano  Malavolta</h2>   </div>    
  • 44. Built-in helpers To iterate over a list each Inside the block, you can use this to reference the element being iterated <ul  class="people_list">      {{#each  people}}        <li>{{this}}</li>      {{/each}}    </ul>     {  people:  [  “Ivano",  “Andrea",  “Paolo"  ]  }     <ul  class="people_list">        <li>Ivano</li>      <li>Andrea</li>      <li>Paolo</li>   </ul>    
  • 45. Built-in helpers It renders the block if its argument is not equal to false,  undefined,  null,  []   If / Else The unless helper is the inverse of if <div  class="entry“>   <h1>{{title}}</h1>   {{#if  author}}    <h2>By  {{firstName}}  {{lastName}}</h2>   {{#else}}    <h2>Unknown  author</h1>     {{/if}}   {  title:  "My  first  post!",          author:  undefined  }   }     <div  class="entry“>   <h1>My  first  post!</h1>   <h2>Unknown  author</h2>   </div>    
  • 46. handlebars summary Each Template can contain Expressions and Helpers operating on them The main helpers are: •  with   •  each   •  if  /  else  /unless   You can define your own Helpers that operate on expressions, they return HTML code A template can be (pre)-compiled and must be executed with a context in order to return the final HTML fragment
  • 47. Handlebars •  Why Handlebars •  Handlebars basics •  Usage with Backbone and Require JS
  • 48. Usage with Backbone and Require JS Templates can be seen as special modules So we can have the following: •  a separate HTML file for each template •  a Backbone view can have a dependency to each template •  the template can be executed by using a JSON object of the Backbone model as context
  • 49. Example Dependency to template HTML file It contains a string Compiled template Execution of the template
  • 51. Contact Ivano Malavolta | Gran Sasso Science Institute iivanoo [email protected] www.ivanomalavolta.com