SlideShare uma empresa Scribd logo
1 de 51
Baixar para ler offline
Gran Sasso Science Institute
Ivano Malavolta
Handlebars
& Require JS
Roadmap
•  Introduction
•  Require JS
•  Handlebars
•  Conclusions
I implemented all best practices and advices in this
presentation in a generic app template available here:

https://github.com/iivanoo/cordovaboilerplate
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 website

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
Require JS
RequireJS is a JavaScript file and module loader
Using a modular script loader like Require JS 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 files 
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
6
7
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 object 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 placeholder 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 in the result"
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
+ 39 380 70 21 600
Contact
Ivano Malavolta |
Gran Sasso Science Institute
iivanoo
ivano.malavolta@univaq.it
www.ivanomalavolta.com

Mais conteúdo relacionado

Mais procurados

Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 

Mais procurados (20)

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
MVC Frameworks for building PHP Web Applications
MVC Frameworks for building PHP Web ApplicationsMVC Frameworks for building PHP Web Applications
MVC Frameworks for building PHP Web Applications
 
C# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASPC# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASP
 
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Angular js
Angular jsAngular js
Angular js
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
Angularjs architecture
Angularjs architectureAngularjs architecture
Angularjs architecture
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
PHP & MVC
PHP & MVCPHP & MVC
PHP & MVC
 
Require.JS
Require.JSRequire.JS
Require.JS
 

Semelhante a Handlebars and Require.js

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 

Semelhante a Handlebars and Require.js (20)

[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
III - Better angularjs
III - Better angularjsIII - Better angularjs
III - Better angularjs
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
Working with AngularJS
Working with AngularJSWorking with AngularJS
Working with AngularJS
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
Web component driven development
Web component driven developmentWeb component driven development
Web component driven development
 
RequireJS
RequireJSRequireJS
RequireJS
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
 
Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4 Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4
 
Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
 
End to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJSEnd to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJS
 
Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
 

Mais de Ivano Malavolta

Mais de Ivano Malavolta (20)

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

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Handlebars and Require.js

  • 1. Gran Sasso Science Institute Ivano Malavolta Handlebars & Require JS
  • 2. Roadmap •  Introduction •  Require JS •  Handlebars •  Conclusions I implemented all best practices and advices in this presentation in a generic app template available here: https://github.com/iivanoo/cordovaboilerplate
  • 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 website 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. Require JS RequireJS is a JavaScript file and module loader Using a modular script loader like Require JS 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 files 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 6 7
  • 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 object 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 placeholder 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 in the result"
  • 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. + 39 380 70 21 600 Contact Ivano Malavolta | Gran Sasso Science Institute iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com