SlideShare a Scribd company logo
Fundamentals of Knockout JS
26 march 2014, Timisoara
Flavius-Radu Demian
Software developer, Avaelgo
I really like programming, web and mobile especially.
Please feel free to ask questions any time and don’t be shy because
Knowledge is power 
flaviusdemian91@yahoo.com | flavius.demian@gmail.com | @slowarad
Expectations
Learn how the MVVM pattern works
Learn the basics of Knockout JS
Learn the advantages and limitations of Knockout JS => when to
use it and when not to
Understand that knockout want to be friends to everyone 
Expectations
And the most important expectations is:
Make you curious  => go home and try it and/or
convince your PM at work in order for him to let you use it
Agenda
The MVVM Pattern
Welcome to Knockout
Headline Features
Bindings
Templates
Mapping and unmapping
Navigation
Testing
Samples
Conclusions
Whats is MVVM
The Model-View-View Model (MVVM) pattern is a software architectural design
pattern.
This pattern emerged in 2005 to support the inherent data binding functionality
offered by XAML subsystems such as WPF and Silverlight.
Related patterns: MVC ( ex: asp .net mvc), MVP ( ex: windows forms) . MVVM (
ex: WPF, Silverlight) is based on MVC and it is a specialization of MVP.
More explanations at this link.
What is MVVM - Model
The Model encapsulates the domain model, business logic and may include data
access.
User
{
username,
firstname,
lastname,
email
}
What is MVVM - View
The view is the application’s User Interface (UI).
It defines the appearance of the UI and its visual elements and controls such as
text boxes and buttons.
The view may also implement view behavior such as animations and transitions.
What is MVVM - ViewModel
The view model is responsible for holding application state, handling
presentation logic and exposing application data and operations (commands) to
the view such (ex: LoadCustomers).
It acts as the intermediary ( glue) between the view and model.
The view model retrieves data from the model and exposes it to the view as
properties in a form that the view can easily digest.
MVVM Benefits
As with other separation patterns such as MVC, MVVM facilitates the
separation of concerns.
The advantages of separating concerns in the MVVM manner include the
facilitation of the following:
Developer/Designer Collaboration without Conflict
Testable Code
Code Maintainability
Knockout JS
Knockout is a JavaScript library that helps you to create rich, responsive display
and editor user interfaces with a clean underlying data model.
Any time you have sections of UI that update dynamically (e.g., changing
depending on the user’s actions or when an external data source changes), KO
can help you implement it more simply and maintainably.
http://knockoutjs.com
Knockout JS
Some teasers:
http://knockoutjs.com/examples/cartEditor.html
http://knockoutjs.com/examples/betterList.html
http://knockoutjs.com/examples/animatedTransitions.html
http://learn.knockoutjs.com/WebmailExampleStandalone.html
Headline features
Elegant dependency tracking - automatically updates the right parts of your UI
whenever your data model changes.
Declarative bindings - a simple and obvious way to connect parts of your UI to
your data model. You can construct a complex dynamic UIs easily using
arbitrarily nested binding contexts.
Trivially extensible - implement custom behaviors as new declarative bindings
for easy reuse in just a few lines of code.
Compact - around 13kb after gzipping
Headline features
Pure JavaScript library - works with any server or client-side technology
Can be added on top of your existing web application without requiring major
architectural changes
Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
Open source
Great community
Bindings
Data-bind attributes in html
ko.observable() for the properties
ko.computed() for mixes between properties and/or strings
ko.applyBindings() to activate bindings
Simple Binding Example
<div data-bind=“text: message”></div>
function viewModel () {
this.message: ko.obersvable(“Hello World”);
}
ko.applyBindings(viewModel);
Bindings
Bindings
Observable is a function !
Do not to this:
viewModel.message = ‘hi’;
Do this:
viewModel.message(‘hi’);
Most used bindings
Text
Today's message is: <span data-bind="text: myMessage"></span>
Value
Today's message is: <input type=‘text’ data-bind=“value: myMessage“/>
Html
<div data-bind="html: news"></div>
Most used bindings
Css
<p data-bind="css: sendByMe == false ? 'bubbleLeft' : 'bubbleRight‘ ”></p>
Style
<p data-bind="style: { color: value < 0 ? 'red' : 'black' }"></p>
Attr
<a data-bind="attr: { href: url, title: title}">Custom Link</a>
Control Flow Bindings - foreach
<ul data-bind="foreach: people“>
<li> <p data-bind="text: firstName"></li>
<li> <p data-bind="text: lastName"> </li>
</ul>
ko.applyBindings({
people: [ { firstName: 'Bert', lastName: 'Bertington' },
{ firstName: 'Charles', lastName: 'Charlesforth' }]
});
Control Flow Bindings - If
<ul data-bind="foreach: planets">
<li>Planet: <b data-bind="text: name"> </b>
<div data-bind="if: capital">
Capital: <b data-bind="text: capital.cityName"> </b></div>
</li>
</ul>
ko.applyBindings({
planets: [ { name: 'Mercury', capital: null },
{ name: 'Earth', capital: { cityName: 'Barnsley' } } ]
});
Form Fields Bindings - click
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
var viewModel = {
numberOfClicks : ko.observable(0),
incrementClickCounter : function() {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}
};
Form Fields Bindings - event
<div data-bind="event: { mouseover: showDetails, mouseout: hideDetails }">
Mouse over me </div>
<div data-bind="visible: detailsShown "> Details </div>
var viewModel = {
detailsShown: ko.observable(false),
showDetails: function() {
this.detailsShown(true);
},
hideDetails: function() {
this.detailsShown(false);
} };
Form Fields Bindings - submit
<form data-bind="submit: doSomething">
... form contents go here ...
<button type="submit">Submit</button>
</form>
var viewModel = {
doSomething : function(formElement) {
// ... now do something
}
};
Form Fields Bindings - enable
<p>
<input type='checkbox' data-bind="checked: hasCellphone" />
<span> I have a cellphone </span>
</p>
<p> Your cellphone number:
<input type='text' data-bind="value: cellNumber,
enable: hasCellphone" />
</p>
var viewModel = {
hasCellphone : ko.observable(false),
cellNumber: ko.observable(“”)
};
Form Fields Bindings - hasFocus
<input data-bind="hasFocus: isSelected" />
<span data-bind="visible: isSelected">The textbox has focus</span>
var viewModel = {
isSelected: ko.observable(false),
setIsSelected: function() {
this.isSelected(true)
}
};
Form Fields Bindings - checked
<p>Send me spam:
<input type="checkbox" data-bind="checked: wantsSpam" />
</p>
var viewModel = {
wantsSpam: ko.observable(true) // Initially checked
};
// ... then later ...
viewModel.wantsSpam(false); // The checkbox becomes unchecked
Form Fields Bindings – checked
<div data-bind="visible: wantsSpam"> Preferred flavor of spam:
<div>
<input type="radio" name=“group" value="cherry" data-bind="checked: spamFlavor" /> Cherry
</div>
<div>
<input type="radio" name=“group" value="almond" data-bind="checked: spamFlavor" /> Almond
</div>
</div>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable("almond") // selects only the Almond radio button
};
viewModel.spamFlavor("cherry"); // Now only Cherry radio button is checked
Form Fields Bindings - options
<span>Destination country: </span>
<select data-bind="options: availableCountries"></select>
var viewModel = {
// These are the initial options
availableCountries: ko.observableArray(['France', 'Spain'])
};
// ... then later ...
viewModel.availableCountries.push('China'); // Adds another option
Templates
There are two main ways of using templates: native and string based
Native templating is the mechanism that underpins foreach, if, with, and other
control flow bindings.
Internally, those control flow bindings capture the HTML markup contained in
your element, and use it as a template to render against an arbitrary data item.
This feature is built into Knockout and doesn’t require any external library.
Native named template example
Templates
String-based templating is a way to connect Knockout to a third-party
template engine.
Knockout will pass your model values to the external template engine and
inject the resulting markup string into your document.
String-based Templates
Jquery.tmpl
Mapping
All properties of an object are converted into an observable. If an update would
change the value, it will update the observable.
Arrays are converted into observable arrays. If an update would change the
number of items, it will perform the appropriate add/remove actions
var viewModel = ko.mapping.fromJS(data);
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);
Unmapping
If you want to convert your mapped object back to a regular JS object, use:
var unmapped = ko.mapping.toJS(viewModel);
The mapping and unmapping will also try to keep the order the same as the
original JavaScript array/ observableArray.
Helpers
ko.utils.arrayFirst
ko.utils. arrayFilter
ko.utils.arrayForEach
ko.utils.arrayGetDistinctValues
ko.utils.arrayIndexOf
ko.utils.arrayPushAll
ko.utils.unwrapObservable
unshift – insert at the beggining, shift – removes the first element, reverse, sort,
splice, slice
and lots more…
Navigation
You can implement navigation with Sammy JS ( for example)
http://learn.knockoutjs.com/#/?tutorial=webmail
Validation
You can use Knockout Validation ( for example):
https://github.com/Knockout-Contrib/Knockout-Validation
Support for :
required, min , max, minLenght,
maxLenght, email, pattern, step, date,
number, digit, date, equal, not eqal
http://jsfiddle.net/slown1/bzkE5/2/
Testing
You can use Jasmine and Phantom JS ( for example):
http://kylehodgson.com/2012/11/29/knockoutjs-and-testing/
describe("Person Name", function() {
it("computes fullName based on firstName and lastName",
function() {
var target = new PersonNameViewModel("Ada","Lovelace");
expect(target.fullName()).toBe("Ada Lovelace");
});
});
Let’s see some code
My Demo 
http://193.226.9.134:8000/MobileServicesWebDemo/
Conclusions
Elegant dependency tracking
Declarative bindings
Trivially extensible
Pure JavaScript library
Can be added on top of your existing web application
Works on any mainstream browser Open source
Great community
Developer/Designer
Collaboration without Conflict
Testable Code
Thanks
More samples
http://knockoutjsdemo.apphb.com/Example/HelloWorld
http://learn.knockoutjs.com/#/?tutorial=intro

More Related Content

PDF
An introduction to knockout.js
PDF
Knockout js session
PPTX
Introduction to Knockoutjs
PPT
KnockoutJS and MVVM
PPTX
Knockout js
KEY
Knockout.js presentation
PPTX
Knockout.js
PPTX
An introduction to knockout.js
Knockout js session
Introduction to Knockoutjs
KnockoutJS and MVVM
Knockout js
Knockout.js presentation
Knockout.js

What's hot (20)

PPTX
KnockOutjs from Scratch
PPTX
Dom selecting & jQuery
PDF
JavaScript and BOM events
PPTX
MVVM Lights
PDF
Introduction to backbone js
PDF
Web Components + Backbone: a Game-Changing Combination
PDF
AngularJS: an introduction
PPTX
Harness jQuery Templates and Data Link
PPTX
Angular Data Binding
PDF
Levent-Gurses' Introduction to Web Components & Polymer
PPTX
MVVM - Model View ViewModel
PPTX
Jqueryppt (1)
POT
Beginning In J2EE
PDF
Difference between java script and jquery
PDF
A brave new web - A talk about Web Components
PPTX
MVC Puree - Approaches to MVC with Umbraco
PDF
Introduction to javascript templating using handlebars.js
PDF
Javascript and DOM
PDF
Introduction to AngularJS
PPTX
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
KnockOutjs from Scratch
Dom selecting & jQuery
JavaScript and BOM events
MVVM Lights
Introduction to backbone js
Web Components + Backbone: a Game-Changing Combination
AngularJS: an introduction
Harness jQuery Templates and Data Link
Angular Data Binding
Levent-Gurses' Introduction to Web Components & Polymer
MVVM - Model View ViewModel
Jqueryppt (1)
Beginning In J2EE
Difference between java script and jquery
A brave new web - A talk about Web Components
MVC Puree - Approaches to MVC with Umbraco
Introduction to javascript templating using handlebars.js
Javascript and DOM
Introduction to AngularJS
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
Ad

Viewers also liked (11)

PPTX
Knockout.js explained
PDF
Knockout js (Dennis Haney)
PPTX
knockout.js
PPTX
Knockout js
PPTX
Knockout (support slides for presentation)
PPT
Knockout.js
PPTX
Knockout js
PPTX
Knockout JS Development - a Quick Understanding
PPTX
#2 Hanoi Magento Meetup - Part 2: Knockout JS
PPT
Download presentation
PPT
Slideshare Powerpoint presentation
Knockout.js explained
Knockout js (Dennis Haney)
knockout.js
Knockout js
Knockout (support slides for presentation)
Knockout.js
Knockout js
Knockout JS Development - a Quick Understanding
#2 Hanoi Magento Meetup - Part 2: Knockout JS
Download presentation
Slideshare Powerpoint presentation
Ad

Similar to Fundaments of Knockout js (20)

PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
ODP
Introduction to Knockout Js
PPT
MVC Pattern. Flex implementation of MVC
PDF
Knockoutjs databinding
PPTX
MVC & backbone.js
PPTX
Asp.NET MVC
PDF
MVVM & Data Binding Library
PPTX
Asp.net mvc training
PPTX
Building an enterprise app in silverlight 4 and NHibernate
PDF
Rp 6 session 2 naresh bhatia
PPTX
Training: MVVM Pattern
PDF
Client Side MVC & Angular
PPT
MVC
PPTX
Stephen Kennedy Silverlight 3 Deep Dive
PPT
MVC Demystified: Essence of Ruby on Rails
KEY
AngularJS for designers and developers
PDF
Introduction to Angularjs : kishan kumar
PPTX
Introduction to Angularjs
PDF
Spring Framework-II
PDF
Yeoman AngularJS and D3 - A solid stack for web apps
MV* presentation frameworks in Javascript: en garde, pret, allez!
Introduction to Knockout Js
MVC Pattern. Flex implementation of MVC
Knockoutjs databinding
MVC & backbone.js
Asp.NET MVC
MVVM & Data Binding Library
Asp.net mvc training
Building an enterprise app in silverlight 4 and NHibernate
Rp 6 session 2 naresh bhatia
Training: MVVM Pattern
Client Side MVC & Angular
MVC
Stephen Kennedy Silverlight 3 Deep Dive
MVC Demystified: Essence of Ruby on Rails
AngularJS for designers and developers
Introduction to Angularjs : kishan kumar
Introduction to Angularjs
Spring Framework-II
Yeoman AngularJS and D3 - A solid stack for web apps

More from Flavius-Radu Demian (10)

PDF
Mobile growth with Xamarin
PPTX
MVVM frameworks - MvvmCross
PPTX
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
PPTX
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
PDF
ALM on the shoulders of Giants - Visual Studio Online
PPTX
Universal apps
PPTX
Security in windows azure
PPTX
Building a chat app with windows azure mobile
PPTX
Building a chat app with windows azure mobile
PPTX
Building a chat app with windows azure mobile services
Mobile growth with Xamarin
MVVM frameworks - MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
ALM on the shoulders of Giants - Visual Studio Online
Universal apps
Security in windows azure
Building a chat app with windows azure mobile
Building a chat app with windows azure mobile
Building a chat app with windows azure mobile services

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPT
Teaching material agriculture food technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Modernizing your data center with Dell and AMD
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
cuic standard and advanced reporting.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Understanding_Digital_Forensics_Presentation.pptx
Teaching material agriculture food technology
Unlocking AI with Model Context Protocol (MCP)
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
The Rise and Fall of 3GPP – Time for a Sabbatical?
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Modernizing your data center with Dell and AMD
The AUB Centre for AI in Media Proposal.docx
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Monthly Chronicles - July 2025
Mobile App Security Testing_ A Comprehensive Guide.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation_ Review paper, used for researhc scholars
cuic standard and advanced reporting.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MYSQL Presentation for SQL database connectivity

Fundaments of Knockout js

  • 1. Fundamentals of Knockout JS 26 march 2014, Timisoara
  • 2. Flavius-Radu Demian Software developer, Avaelgo I really like programming, web and mobile especially. Please feel free to ask questions any time and don’t be shy because Knowledge is power  flaviusdemian91@yahoo.com | flavius.demian@gmail.com | @slowarad
  • 3. Expectations Learn how the MVVM pattern works Learn the basics of Knockout JS Learn the advantages and limitations of Knockout JS => when to use it and when not to Understand that knockout want to be friends to everyone 
  • 4. Expectations And the most important expectations is: Make you curious  => go home and try it and/or convince your PM at work in order for him to let you use it
  • 5. Agenda The MVVM Pattern Welcome to Knockout Headline Features Bindings Templates Mapping and unmapping Navigation Testing Samples Conclusions
  • 6. Whats is MVVM The Model-View-View Model (MVVM) pattern is a software architectural design pattern. This pattern emerged in 2005 to support the inherent data binding functionality offered by XAML subsystems such as WPF and Silverlight. Related patterns: MVC ( ex: asp .net mvc), MVP ( ex: windows forms) . MVVM ( ex: WPF, Silverlight) is based on MVC and it is a specialization of MVP. More explanations at this link.
  • 7. What is MVVM - Model The Model encapsulates the domain model, business logic and may include data access. User { username, firstname, lastname, email }
  • 8. What is MVVM - View The view is the application’s User Interface (UI). It defines the appearance of the UI and its visual elements and controls such as text boxes and buttons. The view may also implement view behavior such as animations and transitions.
  • 9. What is MVVM - ViewModel The view model is responsible for holding application state, handling presentation logic and exposing application data and operations (commands) to the view such (ex: LoadCustomers). It acts as the intermediary ( glue) between the view and model. The view model retrieves data from the model and exposes it to the view as properties in a form that the view can easily digest.
  • 10. MVVM Benefits As with other separation patterns such as MVC, MVVM facilitates the separation of concerns. The advantages of separating concerns in the MVVM manner include the facilitation of the following: Developer/Designer Collaboration without Conflict Testable Code Code Maintainability
  • 11. Knockout JS Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably. http://knockoutjs.com
  • 13. Headline features Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes. Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts. Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code. Compact - around 13kb after gzipping
  • 14. Headline features Pure JavaScript library - works with any server or client-side technology Can be added on top of your existing web application without requiring major architectural changes Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others) Open source Great community
  • 15. Bindings Data-bind attributes in html ko.observable() for the properties ko.computed() for mixes between properties and/or strings ko.applyBindings() to activate bindings
  • 16. Simple Binding Example <div data-bind=“text: message”></div> function viewModel () { this.message: ko.obersvable(“Hello World”); } ko.applyBindings(viewModel);
  • 18. Bindings Observable is a function ! Do not to this: viewModel.message = ‘hi’; Do this: viewModel.message(‘hi’);
  • 19. Most used bindings Text Today's message is: <span data-bind="text: myMessage"></span> Value Today's message is: <input type=‘text’ data-bind=“value: myMessage“/> Html <div data-bind="html: news"></div>
  • 20. Most used bindings Css <p data-bind="css: sendByMe == false ? 'bubbleLeft' : 'bubbleRight‘ ”></p> Style <p data-bind="style: { color: value < 0 ? 'red' : 'black' }"></p> Attr <a data-bind="attr: { href: url, title: title}">Custom Link</a>
  • 21. Control Flow Bindings - foreach <ul data-bind="foreach: people“> <li> <p data-bind="text: firstName"></li> <li> <p data-bind="text: lastName"> </li> </ul> ko.applyBindings({ people: [ { firstName: 'Bert', lastName: 'Bertington' }, { firstName: 'Charles', lastName: 'Charlesforth' }] });
  • 22. Control Flow Bindings - If <ul data-bind="foreach: planets"> <li>Planet: <b data-bind="text: name"> </b> <div data-bind="if: capital"> Capital: <b data-bind="text: capital.cityName"> </b></div> </li> </ul> ko.applyBindings({ planets: [ { name: 'Mercury', capital: null }, { name: 'Earth', capital: { cityName: 'Barnsley' } } ] });
  • 23. Form Fields Bindings - click You've clicked <span data-bind="text: numberOfClicks"></span> times <button data-bind="click: incrementClickCounter">Click me</button> var viewModel = { numberOfClicks : ko.observable(0), incrementClickCounter : function() { var previousCount = this.numberOfClicks(); this.numberOfClicks(previousCount + 1); } };
  • 24. Form Fields Bindings - event <div data-bind="event: { mouseover: showDetails, mouseout: hideDetails }"> Mouse over me </div> <div data-bind="visible: detailsShown "> Details </div> var viewModel = { detailsShown: ko.observable(false), showDetails: function() { this.detailsShown(true); }, hideDetails: function() { this.detailsShown(false); } };
  • 25. Form Fields Bindings - submit <form data-bind="submit: doSomething"> ... form contents go here ... <button type="submit">Submit</button> </form> var viewModel = { doSomething : function(formElement) { // ... now do something } };
  • 26. Form Fields Bindings - enable <p> <input type='checkbox' data-bind="checked: hasCellphone" /> <span> I have a cellphone </span> </p> <p> Your cellphone number: <input type='text' data-bind="value: cellNumber, enable: hasCellphone" /> </p> var viewModel = { hasCellphone : ko.observable(false), cellNumber: ko.observable(“”) };
  • 27. Form Fields Bindings - hasFocus <input data-bind="hasFocus: isSelected" /> <span data-bind="visible: isSelected">The textbox has focus</span> var viewModel = { isSelected: ko.observable(false), setIsSelected: function() { this.isSelected(true) } };
  • 28. Form Fields Bindings - checked <p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /> </p> var viewModel = { wantsSpam: ko.observable(true) // Initially checked }; // ... then later ... viewModel.wantsSpam(false); // The checkbox becomes unchecked
  • 29. Form Fields Bindings – checked <div data-bind="visible: wantsSpam"> Preferred flavor of spam: <div> <input type="radio" name=“group" value="cherry" data-bind="checked: spamFlavor" /> Cherry </div> <div> <input type="radio" name=“group" value="almond" data-bind="checked: spamFlavor" /> Almond </div> </div> var viewModel = { wantsSpam: ko.observable(true), spamFlavor: ko.observable("almond") // selects only the Almond radio button }; viewModel.spamFlavor("cherry"); // Now only Cherry radio button is checked
  • 30. Form Fields Bindings - options <span>Destination country: </span> <select data-bind="options: availableCountries"></select> var viewModel = { // These are the initial options availableCountries: ko.observableArray(['France', 'Spain']) }; // ... then later ... viewModel.availableCountries.push('China'); // Adds another option
  • 31. Templates There are two main ways of using templates: native and string based Native templating is the mechanism that underpins foreach, if, with, and other control flow bindings. Internally, those control flow bindings capture the HTML markup contained in your element, and use it as a template to render against an arbitrary data item. This feature is built into Knockout and doesn’t require any external library.
  • 33. Templates String-based templating is a way to connect Knockout to a third-party template engine. Knockout will pass your model values to the external template engine and inject the resulting markup string into your document.
  • 35. Mapping All properties of an object are converted into an observable. If an update would change the value, it will update the observable. Arrays are converted into observable arrays. If an update would change the number of items, it will perform the appropriate add/remove actions var viewModel = ko.mapping.fromJS(data); // Every time data is received from the server: ko.mapping.fromJS(data, viewModel);
  • 36. Unmapping If you want to convert your mapped object back to a regular JS object, use: var unmapped = ko.mapping.toJS(viewModel); The mapping and unmapping will also try to keep the order the same as the original JavaScript array/ observableArray.
  • 38. Navigation You can implement navigation with Sammy JS ( for example) http://learn.knockoutjs.com/#/?tutorial=webmail
  • 39. Validation You can use Knockout Validation ( for example): https://github.com/Knockout-Contrib/Knockout-Validation Support for : required, min , max, minLenght, maxLenght, email, pattern, step, date, number, digit, date, equal, not eqal http://jsfiddle.net/slown1/bzkE5/2/
  • 40. Testing You can use Jasmine and Phantom JS ( for example): http://kylehodgson.com/2012/11/29/knockoutjs-and-testing/ describe("Person Name", function() { it("computes fullName based on firstName and lastName", function() { var target = new PersonNameViewModel("Ada","Lovelace"); expect(target.fullName()).toBe("Ada Lovelace"); }); });
  • 41. Let’s see some code My Demo  http://193.226.9.134:8000/MobileServicesWebDemo/
  • 42. Conclusions Elegant dependency tracking Declarative bindings Trivially extensible Pure JavaScript library Can be added on top of your existing web application Works on any mainstream browser Open source Great community Developer/Designer Collaboration without Conflict Testable Code