SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
Templates, Control of Flow, and
Containerless Bindings
John Papa
@john_papa
http://johnpapa.net
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Templates
§  Re-use code
§  Encapsulate responsibility for a specific rendering
§  Knockout supports many popular templating engines
o 
o 

jQuery Templates
Underscore

§  Knockout has native templates
Named Templates in <script> tags
§  Encapsulate a template for re-use

<div	
  data-­‐bind="template:	
  {name:	
  'personTmpl'}"></div>	
  	
  
	
  
<script	
  type="text/html"	
  id="personTmpl">	
  	
  	
  	
  	
  	
  
	
  <span	
  data-­‐bind="text:	
  firstName"></span>	
  
	
  <span	
  data-­‐bind="text:	
  lastName"></span>	
  
	
  <button	
  data-­‐bind="click:selectPerson">Add</button>	
  
</script>	
  	
  
DEMO
Named Templates
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Control of Flow

if

•  If truthy condition

ifnot

•  If falsy condition

foreach
with

•  Execute for each item in a list

•  Shortcut to execute for the object
Control of Flow with a Template
§  Pass the context for the template with “foreach”
<tbody	
  	
  
	
  data-­‐bind="template:	
  {name:	
  'productsTmpl',	
  foreach:	
  lines}">	
  
</tbody>	
  
	
  
<script	
  type="text/html"	
  id="productsTmpl">	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  <tr>	
  	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  <td	
  style="width:	
  100px;">	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  <input	
  	
  	
  	
  data-­‐bind="value:	
  quantity"	
  />	
  
	
   	
  
	
  	
  	
  	
  	
  </td>	
  	
  
	
  
	
  	
  	
  	
  	
  ...	
  
	
  </tr>	
  
</script>	
  	
  	
  
Conditional Control of Flow

Any “truthy” expression

<p	
  data-­‐bind="if:	
  lines().length	
  >	
  0">	
  
	
  <span>Total	
  value:</span>	
  
	
  <span	
  data-­‐bind="text:	
  grandTotal()"></span>	
  
</p>	
  	
  
Change Context “with“Control of Flow

<div>	
  	
  	
  
	
  <div	
  data-­‐bind="text:	
  model().brand"></div>	
  
	
  <div	
  data-­‐bind="text:	
  model().name"></div>	
  
</div>	
  

Change the context
with “with”
<div	
  data-­‐bind="with:	
  model">	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  <div	
  data-­‐bind="text:	
  brand"></div>	
  
	
  <div	
  data-­‐bind="text:	
  name"></div>	
  
</div>	
  
Parent Binding Contexts
§  Sometimes in templates you want to change
data binding scope (Data Context)
o 
o 
o 
o 

$data
$parent
$parents
$root

	
  
<button	
  	
  data-­‐bind="click:	
  $parent.addItem">Add</button>	
  	
  
	
  
DEMO
Control of Flow and Binding Contexts
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Inline Templates with Control of Flow
§  If not reusing it, there is no need to name a template
§  Control of flow elements create an implicit template
<tbody	
  data-­‐bind="foreach:	
  lines">	
  
<tbody	
  	
  
	
  <tr>	
  	
  
	
  data-­‐bind="template:	
  {name:	
  'productsTmpl',	
  foreach:	
  lines}">	
  
	
  <td	
  style="width:	
  100px;">	
  
</tbody>	
  
Template is
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  <input	
  data-­‐bind="value:	
  qty"/>	
  
	
  
	
   	
  </td>	
  	
  
<script	
  type="text/html"	
  id="productsTmpl">	
  	
  	
  	
  	
  	
  	
  	
  	
  	
   created
anonymously
	
  ...	
  
	
  <tr>	
  	
  
and implicitly
	
  </tr>	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  <td	
  style="width:	
  100px;">	
  
</tbody>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  <input	
  	
  	
  	
  data-­‐bind="value:	
  qty"	
  />	
  
	
   	
  
	
  	
  	
  	
  	
  </td>	
  	
  
	
  
	
  	
  	
  	
  	
  ...	
  
	
  </tr>	
  
</script>	
  	
  	
  
Knockout’s Native Template Engine
§  Templates inside DOM elements
o 
o 

<script>
Other DOM elements like <div>

§  Anonymous / Inline templates
o 
o 

All Part of the
Native Template Engine
in Knockout

Templates without a name
Shortcuts to Anonymous template binding
o 
o 
o 
o 

if
ifnot
with
foreach

No external
templating dependency
if and ifnot
<div	
  data-­‐bind="template:	
  {if:	
  isSelected}">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  
	
  
<div	
  data-­‐bind="if:	
  isSelected">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  

<div	
  data-­‐bind="template:	
  {ifnot:	
  isSelected}">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  
	
  
<div	
  data-­‐bind="ifnot:	
  isSelected">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  

“if” shortcut

“ifnot” shortcut
foreach and with
<div	
  data-­‐bind="template:	
  {foreach:	
  products}">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  
	
  
<div	
  data-­‐bind="foreach:	
  products">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  

<div	
  data-­‐bind="template:	
  	
  
	
  	
  	
  {if:	
  selectedProduct,	
  data:	
  selectedProduct}">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  
	
  
<div	
  data-­‐bind="with:	
  selectedProduct">	
  
	
  	
  	
  	
  <span	
  data-­‐bind="text:name"></span>	
  
</div>	
  

“foreach“
shortcut

“with”
shortcut
DEMO
Native Template Engine: Inline Templates
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Dynamically Change Templates
§  Swap between multiple templates
§  Bind the name of the template
<div	
  data-­‐bind="template:	
  {name:	
  templateChoice}">	
  	
  
<script	
  type="text/html"	
  id="tmplSummary">	
  	
  
	
  	
  	
  ...	
  	
  	
  	
  	
  	
  	
  	
  	
  
</script>	
  	
  	
  
<script	
  type="text/html"	
  id="tmplDetails">	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  ...	
  	
  	
  	
  	
  	
  	
  	
  	
  
</script>	
  
my.vm.templateChoice	
  =	
  function	
  ()	
  {	
  
	
  	
  	
  	
  return	
  showDetails()	
  ?	
  "tmplDetails"	
  :	
  "tmplSummary";	
  	
  	
  	
  	
  	
  
};	
  	
  
	
  
Control of Flow to Toggle Templates
§  if and ifnot bindings
<div	
  data-­‐bind="ifnot:	
  showDetails()">	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  ...	
  
</div>	
  
<div	
  data-­‐bind="if:	
  showDetails()">	
  	
  
	
  	
  	
  	
  ...	
  
</div>	
  	
  
	
  
my.vm.showDetails	
  =	
  ko.observable(false);	
  
DEMO
Dynamically Choosing a Template
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Template Bindings
name
foreach
data
afterRender
afterAdd
beforeRemove

•  Id of an element that contains the template

•  Renders the template in foreach mode
•  (once for each item)
•  Object to supply as data for the template.
•  If omitted, uses foreach context or the current context
•  Callback invoked after DOM elements are rendered

•  Callback invoked after DOM elements are added

•  Callback invoked before DOM elements are removed
Template Binding Helpers

Callback to a method
<ul	
  data-­‐bind="template:	
  {	
  
in the viewmodel
	
  	
  	
  	
  name:	
  'friendsTemplate',	
  
	
  	
  	
  	
  foreach:	
  model().Friends,	
  
	
  	
  	
  	
  beforeRemove:	
  showAni,	
  
	
  	
  	
  	
  beforeRemove:	
  function(elem)	
  {	
  $(elem).slideUp()	
  },	
  
	
  	
  	
  	
  afterAdd:	
  hideAni}">	
  
	
  	
  	
  	
  afterAdd:	
  function(elem)	
  {	
  $(elem).hide().slideDown()	
  }	
  }">	
  
</ul>	
  
DEMO
Template Binding Helpers
Outline
§ 
§ 
§ 
§ 
§ 
§ 
§ 

Named Templates
Control of Flow
Binding Contexts
Inline Templates
Dynamically Choosing a Template
Template Binding Helpers
Containerless Bindings
Containerless Control of Flow Bindings
§  Comment syntax
o 

Unlike traditional Javascript template in <script>

§  Use a template, without having a template!
o 
o 

What?!
He’s nuts!

§  Comment based control flow syntax
o 
o 
o 
o 
o 

if
ifnot
foreach
with
template

All Part of the
Native Template Engine
in Knockout
Containerless Examples
Reduces Unneeded
Elements

<!-­‐-­‐	
  ko	
  with:	
  selectedPerson	
  -­‐-­‐>	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  <span	
  data-­‐bind="text:	
  name"></span>	
  
	
  	
  <input	
  data-­‐bind="value:	
  salary"></input>	
  
<!-­‐-­‐	
  /ko	
  -­‐-­‐>	
  
	
  

Moves binding logic
outside of elements

<ul>	
  
	
  	
  	
  	
  <li	
  class="category">Acoustic	
  Guitars<li>	
  
	
  	
  	
  	
  <!-­‐-­‐	
  ko	
  foreach:acousticProducts	
  -­‐-­‐>	
  
	
  	
  	
  	
  <li>	
  
	
  	
  	
  	
  	
  	
  	
  	
  <span	
  data-­‐bind="text:	
  shortDesc></span>	
  
	
  	
  	
  	
  </li>	
  
	
  	
  	
  	
  <!-­‐-­‐	
  /ko	
  -­‐-­‐>	
  
</ul>	
  
	
  
DEMO
Containerless/Comment Bindings
Summary
§  Native Template Engine
o 

Named Templates and Anonymous / Inline Templates

§  Control of Flow
o 

if, ifnot, with, foreach, template

§  Binding Contexts
o 

$data, $parent, $parents, $root

§  Dynamically Choosing a Template
o 

template: {name: myObservableProperty}

§  Template Binding Helpers
o 

name, data, foreach, afterRender, afterAdd, beforeRemove

§  Containerless/Comment Bindings
o 

<!– ko foreach: products -->

§  External Templates
o 

https://github.com/ifandelse/Knockout.js-External-Template-Engine
For more in-depth online developer training visit

on-demand content from authors you trust

Weitere ähnliche Inhalte

Was ist angesagt?

The project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicerThe project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicer
Andrei Hortúa
 
От экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшенОт экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшен
Dmitry Makhnev
 

Was ist angesagt? (19)

Html5, css3 y js
Html5, css3 y jsHtml5, css3 y js
Html5, css3 y js
 
Stripes Framework
Stripes FrameworkStripes Framework
Stripes Framework
 
Html5 and web technology update
Html5 and web technology updateHtml5 and web technology update
Html5 and web technology update
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
 
Polymer
PolymerPolymer
Polymer
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
Template-based Modular Architecture
Template-based Modular ArchitectureTemplate-based Modular Architecture
Template-based Modular Architecture
 
The project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicerThe project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicer
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and Bling
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)
 
Blockly
BlocklyBlockly
Blockly
 
Mvc & java script
Mvc & java scriptMvc & java script
Mvc & java script
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
От экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшенОт экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшен
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
Лабораторная работа №1
Лабораторная работа №1Лабораторная работа №1
Лабораторная работа №1
 

Andere mochten auch

منجزات المدرسة لشهر صفر1
منجزات المدرسة لشهر صفر1منجزات المدرسة لشهر صفر1
منجزات المدرسة لشهر صفر1
tamma07
 
Educational Certificates
Educational CertificatesEducational Certificates
Educational Certificates
Avirup Kanjilal
 

Andere mochten auch (20)

منجزات المدرسة لشهر صفر1
منجزات المدرسة لشهر صفر1منجزات المدرسة لشهر صفر1
منجزات المدرسة لشهر صفر1
 
Educational Certificates
Educational CertificatesEducational Certificates
Educational Certificates
 
Articolo su La voce del Trentino
Articolo su La voce del Trentino Articolo su La voce del Trentino
Articolo su La voce del Trentino
 
Cara membuat blog
Cara membuat blogCara membuat blog
Cara membuat blog
 
Knockout mvvm-m1-slides
Knockout mvvm-m1-slidesKnockout mvvm-m1-slides
Knockout mvvm-m1-slides
 
Knockout mvvm-m2-slides
Knockout mvvm-m2-slidesKnockout mvvm-m2-slides
Knockout mvvm-m2-slides
 
Slideshar daniel cabezas
Slideshar daniel cabezasSlideshar daniel cabezas
Slideshar daniel cabezas
 
Udsphoto2
Udsphoto2Udsphoto2
Udsphoto2
 
Knockout mvvm-m4-slides
Knockout mvvm-m4-slidesKnockout mvvm-m4-slides
Knockout mvvm-m4-slides
 
Knockout mvvm-m6-slides
Knockout mvvm-m6-slidesKnockout mvvm-m6-slides
Knockout mvvm-m6-slides
 
Udsphoto2
Udsphoto2Udsphoto2
Udsphoto2
 
The Health Care Law and You
The Health Care Law and YouThe Health Care Law and You
The Health Care Law and You
 
Funding Opportunities
Funding OpportunitiesFunding Opportunities
Funding Opportunities
 
Interview preparation
Interview preparationInterview preparation
Interview preparation
 
Ejercicios subnetting
Ejercicios subnettingEjercicios subnetting
Ejercicios subnetting
 
The LVHN Teleburn Program
The LVHN Teleburn ProgramThe LVHN Teleburn Program
The LVHN Teleburn Program
 
Distance Learning & Telemedicine Grant Program
Distance Learning & Telemedicine Grant ProgramDistance Learning & Telemedicine Grant Program
Distance Learning & Telemedicine Grant Program
 
Uso practico de git
Uso practico de gitUso practico de git
Uso practico de git
 
Morning Plenary Session
Morning Plenary SessionMorning Plenary Session
Morning Plenary Session
 
Industrial Health and Telehealth in Kentucky
Industrial Health and Telehealth in KentuckyIndustrial Health and Telehealth in Kentucky
Industrial Health and Telehealth in Kentucky
 

Ähnlich wie Knockout mvvm-m5-slides

TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
Coulawrence
 

Ähnlich wie Knockout mvvm-m5-slides (20)

Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Diazo: Bridging Designers and Programmers
Diazo: Bridging Designers and ProgrammersDiazo: Bridging Designers and Programmers
Diazo: Bridging Designers and Programmers
 
Angular JS Introduction
Angular JS IntroductionAngular JS Introduction
Angular JS Introduction
 
Fly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using AngularFly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using Angular
 
Design Systems, Pattern Libraries & WordPress
Design Systems, Pattern Libraries & WordPressDesign Systems, Pattern Libraries & WordPress
Design Systems, Pattern Libraries & WordPress
 
hellowired_instructions
hellowired_instructionshellowired_instructions
hellowired_instructions
 
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
Introduction to web components
Introduction to web componentsIntroduction to web components
Introduction to web components
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
smoke1272528461
smoke1272528461smoke1272528461
smoke1272528461
 

Mehr von MasterCode.vn

Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
MasterCode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
MasterCode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
MasterCode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
MasterCode.vn
 

Mehr von MasterCode.vn (20)

Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vnPd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
 
Why apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vnWhy apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vn
 
Dzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vnDzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vn
 
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vnGoogle công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
 
Nghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vnNghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vn
 
Lập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vnLập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vn
 
Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
 
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vnPd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
 
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vnPd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
 
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vnPdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
 
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vnPdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vnPdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vnPdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vnPdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vnPdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vnPdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vnPdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Kürzlich hochgeladen (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

Knockout mvvm-m5-slides

  • 1. Templates, Control of Flow, and Containerless Bindings John Papa @john_papa http://johnpapa.net
  • 2. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 3. Templates §  Re-use code §  Encapsulate responsibility for a specific rendering §  Knockout supports many popular templating engines o  o  jQuery Templates Underscore §  Knockout has native templates
  • 4. Named Templates in <script> tags §  Encapsulate a template for re-use <div  data-­‐bind="template:  {name:  'personTmpl'}"></div>       <script  type="text/html"  id="personTmpl">              <span  data-­‐bind="text:  firstName"></span>    <span  data-­‐bind="text:  lastName"></span>    <button  data-­‐bind="click:selectPerson">Add</button>   </script>    
  • 6. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 7. Control of Flow if •  If truthy condition ifnot •  If falsy condition foreach with •  Execute for each item in a list •  Shortcut to execute for the object
  • 8. Control of Flow with a Template §  Pass the context for the template with “foreach” <tbody      data-­‐bind="template:  {name:  'productsTmpl',  foreach:  lines}">   </tbody>     <script  type="text/html"  id="productsTmpl">                      <tr>                        <td  style="width:  100px;">                            <input        data-­‐bind="value:  quantity"  />                </td>                ...    </tr>   </script>      
  • 9. Conditional Control of Flow Any “truthy” expression <p  data-­‐bind="if:  lines().length  >  0">    <span>Total  value:</span>    <span  data-­‐bind="text:  grandTotal()"></span>   </p>    
  • 10. Change Context “with“Control of Flow <div>        <div  data-­‐bind="text:  model().brand"></div>    <div  data-­‐bind="text:  model().name"></div>   </div>   Change the context with “with” <div  data-­‐bind="with:  model">                                              <div  data-­‐bind="text:  brand"></div>    <div  data-­‐bind="text:  name"></div>   </div>  
  • 11. Parent Binding Contexts §  Sometimes in templates you want to change data binding scope (Data Context) o  o  o  o  $data $parent $parents $root   <button    data-­‐bind="click:  $parent.addItem">Add</button>      
  • 12. DEMO Control of Flow and Binding Contexts
  • 13. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 14. Inline Templates with Control of Flow §  If not reusing it, there is no need to name a template §  Control of flow elements create an implicit template <tbody  data-­‐bind="foreach:  lines">   <tbody      <tr>      data-­‐bind="template:  {name:  'productsTmpl',  foreach:  lines}">    <td  style="width:  100px;">   </tbody>   Template is                        <input  data-­‐bind="value:  qty"/>        </td>     <script  type="text/html"  id="productsTmpl">                     created anonymously  ...    <tr>     and implicitly  </tr>                      <td  style="width:  100px;">   </tbody>                            <input        data-­‐bind="value:  qty"  />                </td>                ...    </tr>   </script>      
  • 15. Knockout’s Native Template Engine §  Templates inside DOM elements o  o  <script> Other DOM elements like <div> §  Anonymous / Inline templates o  o  All Part of the Native Template Engine in Knockout Templates without a name Shortcuts to Anonymous template binding o  o  o  o  if ifnot with foreach No external templating dependency
  • 16. if and ifnot <div  data-­‐bind="template:  {if:  isSelected}">          <span  data-­‐bind="text:name"></span>   </div>     <div  data-­‐bind="if:  isSelected">          <span  data-­‐bind="text:name"></span>   </div>   <div  data-­‐bind="template:  {ifnot:  isSelected}">          <span  data-­‐bind="text:name"></span>   </div>     <div  data-­‐bind="ifnot:  isSelected">          <span  data-­‐bind="text:name"></span>   </div>   “if” shortcut “ifnot” shortcut
  • 17. foreach and with <div  data-­‐bind="template:  {foreach:  products}">          <span  data-­‐bind="text:name"></span>   </div>     <div  data-­‐bind="foreach:  products">          <span  data-­‐bind="text:name"></span>   </div>   <div  data-­‐bind="template:          {if:  selectedProduct,  data:  selectedProduct}">          <span  data-­‐bind="text:name"></span>   </div>     <div  data-­‐bind="with:  selectedProduct">          <span  data-­‐bind="text:name"></span>   </div>   “foreach“ shortcut “with” shortcut
  • 18. DEMO Native Template Engine: Inline Templates
  • 19. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 20. Dynamically Change Templates §  Swap between multiple templates §  Bind the name of the template <div  data-­‐bind="template:  {name:  templateChoice}">     <script  type="text/html"  id="tmplSummary">          ...                   </script>       <script  type="text/html"  id="tmplDetails">                      ...                   </script>   my.vm.templateChoice  =  function  ()  {          return  showDetails()  ?  "tmplDetails"  :  "tmplSummary";             };      
  • 21. Control of Flow to Toggle Templates §  if and ifnot bindings <div  data-­‐bind="ifnot:  showDetails()">                    ...   </div>   <div  data-­‐bind="if:  showDetails()">            ...   </div>       my.vm.showDetails  =  ko.observable(false);  
  • 23. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 24. Template Bindings name foreach data afterRender afterAdd beforeRemove •  Id of an element that contains the template •  Renders the template in foreach mode •  (once for each item) •  Object to supply as data for the template. •  If omitted, uses foreach context or the current context •  Callback invoked after DOM elements are rendered •  Callback invoked after DOM elements are added •  Callback invoked before DOM elements are removed
  • 25. Template Binding Helpers Callback to a method <ul  data-­‐bind="template:  {   in the viewmodel        name:  'friendsTemplate',          foreach:  model().Friends,          beforeRemove:  showAni,          beforeRemove:  function(elem)  {  $(elem).slideUp()  },          afterAdd:  hideAni}">          afterAdd:  function(elem)  {  $(elem).hide().slideDown()  }  }">   </ul>  
  • 27. Outline §  §  §  §  §  §  §  Named Templates Control of Flow Binding Contexts Inline Templates Dynamically Choosing a Template Template Binding Helpers Containerless Bindings
  • 28. Containerless Control of Flow Bindings §  Comment syntax o  Unlike traditional Javascript template in <script> §  Use a template, without having a template! o  o  What?! He’s nuts! §  Comment based control flow syntax o  o  o  o  o  if ifnot foreach with template All Part of the Native Template Engine in Knockout
  • 29. Containerless Examples Reduces Unneeded Elements <!-­‐-­‐  ko  with:  selectedPerson  -­‐-­‐>                      <span  data-­‐bind="text:  name"></span>      <input  data-­‐bind="value:  salary"></input>   <!-­‐-­‐  /ko  -­‐-­‐>     Moves binding logic outside of elements <ul>          <li  class="category">Acoustic  Guitars<li>          <!-­‐-­‐  ko  foreach:acousticProducts  -­‐-­‐>          <li>                  <span  data-­‐bind="text:  shortDesc></span>          </li>          <!-­‐-­‐  /ko  -­‐-­‐>   </ul>    
  • 31. Summary §  Native Template Engine o  Named Templates and Anonymous / Inline Templates §  Control of Flow o  if, ifnot, with, foreach, template §  Binding Contexts o  $data, $parent, $parents, $root §  Dynamically Choosing a Template o  template: {name: myObservableProperty} §  Template Binding Helpers o  name, data, foreach, afterRender, afterAdd, beforeRemove §  Containerless/Comment Bindings o  <!– ko foreach: products --> §  External Templates o  https://github.com/ifandelse/Knockout.js-External-Template-Engine
  • 32. For more in-depth online developer training visit on-demand content from authors you trust