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
Ad

More Related Content

What's hot (20)

KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
Udaya Kumar
ย 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
Kim Hunmin
ย 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
Jussi Pohjolainen
ย 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
Denis Voituron
ย 
Introduction to backbone js
Introduction to backbone jsIntroduction to backbone js
Introduction to backbone js
Mindfire Solutions
ย 
Web Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationWeb Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing Combination
Andrew Rota
ย 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
ย 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
BorisMoore
ย 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
ย 
Levent-Gurses' Introduction to Web Components & Polymer
Levent-Gurses' Introduction to Web Components & PolymerLevent-Gurses' Introduction to Web Components & Polymer
Levent-Gurses' Introduction to Web Components & Polymer
Erik Isaksen
ย 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModel
Dareen Alhiyari
ย 
Jqueryppt (1)
Jqueryppt (1)Jqueryppt (1)
Jqueryppt (1)
AndreaSmile06
ย 
Beginning In J2EE
Beginning In J2EEBeginning In J2EE
Beginning In J2EE
Suthat Rongraung
ย 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
Umar Ali
ย 
A brave new web - A talk about Web Components
A brave new web - A talk about Web ComponentsA brave new web - A talk about Web Components
A brave new web - A talk about Web Components
Michiel De Mey
ย 
MVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with UmbracoMVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with Umbraco
Andy Butland
ย 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.js
Mindfire Solutions
ย 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
Brian Moschel
ย 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
ย 
Iasi code camp 12 october 2013 shadow dom - mihai bรฎrsan
Iasi code camp 12 october 2013   shadow dom - mihai bรฎrsanIasi code camp 12 october 2013   shadow dom - mihai bรฎrsan
Iasi code camp 12 october 2013 shadow dom - mihai bรฎrsan
Codecamp Romania
ย 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
Udaya Kumar
ย 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
Kim Hunmin
ย 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
Jussi Pohjolainen
ย 
Introduction to backbone js
Introduction to backbone jsIntroduction to backbone js
Introduction to backbone js
Mindfire Solutions
ย 
Web Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationWeb Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing Combination
Andrew Rota
ย 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
ย 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
BorisMoore
ย 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
ย 
Levent-Gurses' Introduction to Web Components & Polymer
Levent-Gurses' Introduction to Web Components & PolymerLevent-Gurses' Introduction to Web Components & Polymer
Levent-Gurses' Introduction to Web Components & Polymer
Erik Isaksen
ย 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModel
Dareen Alhiyari
ย 
Jqueryppt (1)
Jqueryppt (1)Jqueryppt (1)
Jqueryppt (1)
AndreaSmile06
ย 
Beginning In J2EE
Beginning In J2EEBeginning In J2EE
Beginning In J2EE
Suthat Rongraung
ย 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
Umar Ali
ย 
A brave new web - A talk about Web Components
A brave new web - A talk about Web ComponentsA brave new web - A talk about Web Components
A brave new web - A talk about Web Components
Michiel De Mey
ย 
MVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with UmbracoMVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with Umbraco
Andy Butland
ย 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.js
Mindfire Solutions
ย 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
Brian Moschel
ย 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
ย 
Iasi code camp 12 october 2013 shadow dom - mihai bรฎrsan
Iasi code camp 12 october 2013   shadow dom - mihai bรฎrsanIasi code camp 12 october 2013   shadow dom - mihai bรฎrsan
Iasi code camp 12 october 2013 shadow dom - mihai bรฎrsan
Codecamp Romania
ย 

Viewers also liked (11)

Knockout.js explained
Knockout.js explainedKnockout.js explained
Knockout.js explained
Paxcel Technologies
ย 
Knockout js (Dennis Haney)
Knockout js (Dennis Haney)Knockout js (Dennis Haney)
Knockout js (Dennis Haney)
JavaScript Meetup HCMC
ย 
knockout.js
knockout.jsknockout.js
knockout.js
Anton Patrushev
ย 
Knockout js
Knockout jsKnockout js
Knockout js
LearningTech
ย 
Knockout (support slides for presentation)
Knockout (support slides for presentation)Knockout (support slides for presentation)
Knockout (support slides for presentation)
Aymeric Gaurat-Apelli
ย 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
Mindfire Solutions
ย 
Knockout js
Knockout jsKnockout js
Knockout js
hhassann
ย 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick Understanding
Udaya Kumar
ย 
#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JS#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JS
Hanoi MagentoMeetup
ย 
Download presentation
Download presentationDownload presentation
Download presentation
webhostingguy
ย 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
elliehood
ย 
Knockout js
Knockout jsKnockout js
Knockout js
LearningTech
ย 
Knockout (support slides for presentation)
Knockout (support slides for presentation)Knockout (support slides for presentation)
Knockout (support slides for presentation)
Aymeric Gaurat-Apelli
ย 
Knockout js
Knockout jsKnockout js
Knockout js
hhassann
ย 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick Understanding
Udaya Kumar
ย 
#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JS#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JS
Hanoi MagentoMeetup
ย 
Download presentation
Download presentationDownload presentation
Download presentation
webhostingguy
ย 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
elliehood
ย 
Ad

Similar to Fundaments of Knockout js (20)

MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
ย 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
Knoldus Inc.
ย 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
ย 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib
ย 
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
Mohammed Arif
ย 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
vrluckyin
ย 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
10Clouds
ย 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
ย 
Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
bwullems
ย 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
ย 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
Betclic Everest Group Tech Team
ย 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
Alexe Bogdan
ย 
MVC
MVCMVC
MVC
akshin
ย 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
MicrosoftFeed
ย 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
codeinmotion
ย 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
ย 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
Appfinz Technologies
ย 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
Manish Shekhawat
ย 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
People Strategists
ย 
Yeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web appsYeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web apps
climboid
ย 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
Roberto Messora
ย 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
Knoldus Inc.
ย 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
ย 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib
ย 
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
Mohammed Arif
ย 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
vrluckyin
ย 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
10Clouds
ย 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
ย 
Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
bwullems
ย 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
ย 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
Alexe Bogdan
ย 
MVC
MVCMVC
MVC
akshin
ย 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
MicrosoftFeed
ย 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
codeinmotion
ย 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
ย 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
Appfinz Technologies
ย 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
Manish Shekhawat
ย 
Yeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web appsYeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web apps
climboid
ย 
Ad

More from Flavius-Radu Demian (10)

Mobile growth with Xamarin
Mobile growth with XamarinMobile growth with Xamarin
Mobile growth with Xamarin
Flavius-Radu Demian
ย 
MVVM frameworks - MvvmCross
MVVM frameworks - MvvmCrossMVVM frameworks - MvvmCross
MVVM frameworks - MvvmCross
Flavius-Radu Demian
ย 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
Flavius-Radu Demian
ย 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
Flavius-Radu Demian
ย 
ALM on the shoulders of Giants - Visual Studio Online
ALM on the shoulders of Giants - Visual Studio OnlineALM on the shoulders of Giants - Visual Studio Online
ALM on the shoulders of Giants - Visual Studio Online
Flavius-Radu Demian
ย 
Universal apps
Universal appsUniversal apps
Universal apps
Flavius-Radu Demian
ย 
Security in windows azure
Security in windows azureSecurity in windows azure
Security in windows azure
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile services
Building a chat app with windows azure mobile servicesBuilding a chat app with windows azure mobile services
Building a chat app with windows azure mobile services
Flavius-Radu Demian
ย 
Mobile growth with Xamarin
Mobile growth with XamarinMobile growth with Xamarin
Mobile growth with Xamarin
Flavius-Radu Demian
ย 
MVVM frameworks - MvvmCross
MVVM frameworks - MvvmCrossMVVM frameworks - MvvmCross
MVVM frameworks - MvvmCross
Flavius-Radu Demian
ย 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
Flavius-Radu Demian
ย 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
Flavius-Radu Demian
ย 
ALM on the shoulders of Giants - Visual Studio Online
ALM on the shoulders of Giants - Visual Studio OnlineALM on the shoulders of Giants - Visual Studio Online
ALM on the shoulders of Giants - Visual Studio Online
Flavius-Radu Demian
ย 
Security in windows azure
Security in windows azureSecurity in windows azure
Security in windows azure
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
ย 
Building a chat app with windows azure mobile services
Building a chat app with windows azure mobile servicesBuilding a chat app with windows azure mobile services
Building a chat app with windows azure mobile services
Flavius-Radu Demian
ย 

Recently uploaded (20)

Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
ย 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
ย 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
ย 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
HCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
HCL Nomad Web โ€“ Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
HCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
panagenda
ย 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
ย 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
ย 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
ย 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
ย 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
HCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
HCL Nomad Web โ€“ Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
HCL Nomad Web โ€“ Best Practices and Managing Multiuser Environments
panagenda
ย 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
ย 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
ย 

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 ๏Š [email protected] | [email protected] | @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