SlideShare a Scribd company logo
1 of 44
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

What's hot

KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from ScratchUdaya Kumar
 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQueryKim Hunmin
 
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 CombinationAndrew Rota
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkBorisMoore
 
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 & PolymerErik Isaksen
 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModelDareen Alhiyari
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jqueryUmar 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 ComponentsMichiel 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 UmbracoAndy 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.jsMindfire Solutions
 
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îrsanCodecamp Romania
 

What's hot (20)

KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
 
Introduction to backbone js
Introduction to backbone jsIntroduction to backbone js
Introduction to backbone js
 
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
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
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
 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModel
 
Jqueryppt (1)
Jqueryppt (1)Jqueryppt (1)
Jqueryppt (1)
 
Beginning In J2EE
Beginning In J2EEBeginning In J2EE
Beginning In J2EE
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
 
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
 
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
 
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
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
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
 

Viewers also liked

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 jshhassann
 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingUdaya 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 JSHanoi MagentoMeetup
 
Download presentation
Download presentationDownload presentation
Download presentationwebhostingguy
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentationelliehood
 

Viewers also liked (11)

Knockout.js explained
Knockout.js explainedKnockout.js explained
Knockout.js explained
 
Knockout js (Dennis Haney)
Knockout js (Dennis Haney)Knockout js (Dennis Haney)
Knockout js (Dennis Haney)
 
knockout.js
knockout.jsknockout.js
knockout.js
 
Knockout js
Knockout jsKnockout js
Knockout js
 
Knockout (support slides for presentation)
Knockout (support slides for presentation)Knockout (support slides for presentation)
Knockout (support slides for presentation)
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Knockout js
Knockout jsKnockout js
Knockout js
 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick Understanding
 
#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
 
Download presentation
Download presentationDownload presentation
Download presentation
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
 

Similar to Fundaments of Knockout js

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 JsKnoldus Inc.
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCAnton Krasnoshchok
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
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 trainingicubesystem
 
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 NHibernatebwullems
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & AngularAlexe Bogdan
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveMicrosoftFeed
 
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 Railscodeinmotion
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developersKai Koenig
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
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 appsclimboid
 

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!
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
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
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
 
MVC
MVCMVC
MVC
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
 
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
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
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
 

More from 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 MvvmCrossFlavius-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 MvvmCrossFlavius-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 OnlineFlavius-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 mobileFlavius-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 mobileFlavius-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 servicesFlavius-Radu Demian
 

More from Flavius-Radu Demian (10)

Mobile growth with Xamarin
Mobile growth with XamarinMobile growth with Xamarin
Mobile growth with Xamarin
 
MVVM frameworks - MvvmCross
MVVM frameworks - MvvmCrossMVVM frameworks - MvvmCross
MVVM frameworks - MvvmCross
 
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
 
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
 
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
 
Universal apps
Universal appsUniversal apps
Universal apps
 
Security in windows azure
Security in windows azureSecurity in windows azure
Security in windows azure
 
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
 
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
 
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
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

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