SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
Knockout Js
By Ravinder Mahajan
-Synerzip
About Me
•I am Ravinder Mahajan, working as a web developer since
beginning of my career.
•I am microsoft certified HTML5 with JavaScript and CSS3
solution provider.
• I love to explore about the latest technologies/libraries.
•In free time I like to travel to different places.
http://www.linkedin.com/pub/ravinder-mahajan/23/508/668
Agenda for this session
• What is knockout js?
• What is MVVM?
• Why to use Knockout js?
• What are observables?
• What are computed properties?
• What are subscribers?
• What are Bindings in knockout?
• Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
What is knockout?
• Knockout is a JavaScript library built mainly
to provide two way binding between HTML
and Data(View model) and gives us a
responsive display.
• Two way binding
HTML In sync ViewModel
Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout js?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
What is MVVM?
MVVM is a pattern which helps us achieve Two way binding
between our HTML page and Data.
• Model: The model represents the actual data and/or
information we are dealing with
• View: The view is something that end user really
interacts with ie the HTML content
• ViewModel: The viewmodel may expose the model
directly, or properties related to the model, for data-
binding in a formatted/Refined or presentable form.
Ex: let us suppose that our Model Contains a lot of detail
about employees however at the UI we only want to
display Name And Age, this is something what is achieved
by ViewModel
Model(Service/DB directly)
View Model
HTML
Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout js?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
Few Examples at the end to demonstrate the same!!!
Why to use knockout
• Declarative Binding: Binding View Models’ properties to HTML is
very easy
Eg: <span data-bind="text: myProperty"></span>
• Automatic Dom refresh: Every time a property changes in View
Model, its associated Dom is automatically refreshed but not the
entire Page
• Dependency Tracking: If a property is dependent on other property
then knockout can easily detect that and can perform further
operations.
• Templating: Knockout provides you with its own templating engine
which is quite fast, however we can also use any of our templating
engines.
Note: Knockout is very light weight and does not have any
dependency on any other js library.
Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
What are observables?
• Observable are knockout properties which holds the Model
properties needed to bind the data to the UI and internally is
responsible for Two way binding.
Example
function MyViewModel(){
this.firstName: ko.observable(‘Ravinder’),
this.lastName: ko.observable(‘Mahajan’)
};
ko.applyBindings(new MyViewModel(),$(‘#personName’));
<span id=‘personName’ data-bind=“text:firstName”> // Ravinder
http://jsfiddle.net/ravindermahajan890/DM67E/
Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
What are computed Observables?
• computed observables are functions that are dependent on
one or more other observables, and will automatically update
whenever any of these dependencies change.
Example:
function MyViewModel(){
this.firstName: ko.observable(‘Ravi’);
this.lastName: ko.observable(‘Jain’);
this.fullName=ko.computed(function(){
return this.firstName()+ this.lastName();
},this);
};
ko.applyBindings(new MyViewModel(),$(‘#personName’));
<span id=‘personName’ data-bind=“text:fullName”> // Ravi Jain
Case1:
First Name:Ravinder
Last Name:Mahajan
Full Name:Ravinder Mahajan
Now if we edit first and Last Name:
Case2:
First Name: Ankit
Last Name: Kumar
Full Name: Ankit Kumar
http://jsfiddle.net/ravindermahajan890/J8Ymw/
Note: Full name always detect the change in First Name and Last
Name by subscribing to them internally and is computed every
time.
Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
What are subscribers?
• Subscriptions are registered to notify any change in the
subscribed properties.
Example 1:
var myViewModel= new MyViewModel();
myViewModel.personName.subscribe(function(newValue) {
alert(“New value is " + newValue);
});
Example 2:
myViewModel.personName.subscribe(function(newValue) {
alert(“New value is " + newValue);
},this,”beforeChange”);
http://jsfiddle.net/ravindermahajan890/qYhTw/3/
Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
What are Bindings in knockout?
Binding is a phenomenon where in we actually bind
the data present in ViewModels to our HTML page
using some pre-defined keyword(s) well understood
by Knockout
Different types of Binding are available:
1. Text , HTML and appearance Bindings
2. Control flow Bindings
3. Form fields Bindings
4. Custom Binding(To be covered Later)
1) Text , HTML and appearance Bindings
• visible binding: Visible binding causes the Dom Element to
switch is visiblity property on the basis of associated Knockout
Property.
Example:
<div data-bind="visible: visiblePropertyName">
You will see this message only when " visiblePropertyName "
holds a true value.
</div>
var viewModel = {
visiblePropertyName : ko.observable(true)
};
viewModel. visiblePropertyName (false);//This div will not be
visible anymore
http://jsfiddle.net/ravindermahajan890/2aYXj/
• Text binding: Text binding causes the associated DOM
element to display the text value of associated property. We
can use it with almost all the elements.
Example 1:
<span data-bind="text: myMessage , visible:myMessage()!=null
"></span>
var viewModel = {
myMessage: ko.observable(null) ,
count:ko.observable(10)
};
viewModel.myMessage(“Welcome to the world of knockout!");
Text Binding
Example 2:
<span data-bind="text:
count()>10?’Ravinder’:’Synerzip’,visible:myMessage()!=null ">
</span>
http://jsfiddle.net/ravindermahajan890/2aYXj/
HTML Binding
• HTML binding first converts the string into its corresponding
HTML value and then binds the data to it.
• The HTML binding causes the associated DOM element to
display the HTML specified by your parameter.
Example:
<div data-bind="html: details"></div>
var viewModel = {
details: ko.observable()
};
viewModel.details("<em>welcome to <i>Synerzip</i></em>");
Output:
“welcome to Synerzip”
Note: It is always preferred to use text binding as it removes
the problem of script inection or if we are using HTML binding,
make sure we encode the text first.
http://jsfiddle.net/ravindermahajan890/8XW43/
CSS Binding
The css binding adds or removes one or more named CSS classes
to the associated DOM element.
Example 1:
<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>
In this example if the currentProfit() evaluates to less than 0 then
the profit warning css would be applied to the Div.
CSS Expression
Example 2:
<div data-bind="css: { profitWarning: currentProfit() < 0, major
highlight: isSevere }">
This example explains that how can we switch between css
classes on the basis of our conditions.
http://jsfiddle.net/ravindermahajan890/k7ys4/1/
Style Binding
The style binding adds or removes one or more style values to
the associated DOM element
Example:
<div data-bind="style: { color: age() < 0 ? 'red' : 'black' }">
Profit Information
</div>
var viewModel = {
age: ko.observable(15)
};
viewModel.age(-50);
In this example the color value would change its property on the
basis of the age() condition.
Attr Binding
The attr binding ia a way to set the value of any attribute for
the associated DOM element. It is useful, when we want to
assign any attribute on the basis of our viewModels( mainly
“src” of an img tag, or the “href” of a link based on values in
your view model, title of any element)
<a data-bind="attr: { href: url, title: details }">
Synerzip
</a>
var viewModel = {
url: ko.observable(“synerzip.html"),
details: ko.observable(“Welcome to Synerzip")
};
2) Control Flow Bindings
Control Flow Bindings are the bindings which control the flow
of application
Different types of Control Flow Binding are:
• Foreach Binding
• If Binding
• Ifnot Binding
• With Binding
Note: ”ifnot” binding is as good as negated if binding so we will
not touch on ifnot binding
foreach Binding
The foreach binding is generally used to render list or tables
where in the value/Properties is an observable array.
Example:
<div data-bind="foreach: people">
<div data-bind="text: name"></div>
</div>
var viewModel = {
people: ko.observableArray([{ name: 'Bert' },{ name:
'Charles' }, { name: 'Denise' }]) };
Output:
Bert
Charles
Denise
http://jsfiddle.net/ravindermahajan890/mC73V/1/
If Binding
The if binding causes your HTML element in your document only
if a specified expression evaluates to true/Non null object.
Example 1:
<div data-bind="if: displayMessage">
<span>My content<span>
</div>
var viewModel={
displayMessage: ko.observable(false)
};
In the above example the div would not take any space in the
DOM and would not be rendered
Example 2:
<div data-bind="if: displayMessage">
<span>My content<span>
</div>
var viewModel={
displayMessage: ko.observable(true)
};
I would be able to see My content on the page as the
displayMessage property evaluates to true
http://jsfiddle.net/ravindermahajan890/KAAxD/
Note: If binding is somewhat similar to visible binding however
the difference is that with “visible” binding the HTML always
remains in the Dom and which at time becomes overhead but in
the case of “if” binding the element is rendered when the
condition evaluates to true and applies bindings to its
descendants only when the “if” binding evaluates to true.
with binding
“The with binding creates a new binding context, so that
descendant elements are bound in the context of a specified
object”
Ex1:
<div data-bind="with: name“>
<span data-bind="text: firstName"> </span>//name.firstName
<span data-bind="text: lastName"> </span>//name.lastName
</div>
var viewModel={
name: {
firstName: ’Ravinder’,
lastName: ‘Mahajan’
}
});
http://jsfiddle.net/ravindermahajan890/drF9L/
Container less Binding
In Container less binding the binding can be easily achieved
without using a container element.
Example 1:
<!-- ko foreach: people -->
<div data-bind="text: name"></div>
<!-- /ko -->
Example 2:
<!-- ko if: displayMessage -->
<span>My content<span>
<!-- /ko -->
Example 3:
<!-- ko with: name>
<span data-bind="text: firstName"> </span>//name.firstName
<span data-bind="text: lastName"> </span>//name.lastName
<!-- /ko -->
http://jsfiddle.net/ravindermahajan890/m2uVt/
3) Form Fields Binding
These are the bindings which are used while
working with Form fields.
Different types of Form field bindings are:
• "click" binding
• “event” binding
• “submit” binding
• “enable” binding
• “value” binding
• “checked” binding
• “options” binding
• "selectedOptions" binding
"click" binding
• The click binding adds an event handler so that your chosen
JavaScript function will be invoked when the associated DOM
element is clicked
Example 1:
<div>You've clicked
<span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
var viewModel = {
numberOfClicks : ko.observable(),
incrementClickCounter : function(data,event) {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}};
In this example clicking on the button would increment the
this.numberOfClicks by1.
“submit” binding
Submit binding is very much similar to click binding on button,
submit binding prevents the default submit action and will call
your method instead.
However, submit has the advantage that it also captures
alternative ways to submit the form, such as pressing
the enter key while typing into a text box.
http://jsfiddle.net/ravindermahajan890/qWg82/2/
“enable” binding
• The enable binding causes the Dom element to be
enabled or disabled on the basis of observable
property
Example 1:
<input type=“text” data-bind='enable: name()!=‘null’,value:
name">
click to enable
</input>
var viewModel = {
this.name: ko.observable(null)
};
http://jsfiddle.net/ravindermahajan890/qWg82/2/
“value” binding
• Value binding binds your elements present in your DOM to
the properties present in view model.
• They are mainly used with form fields such as Input , Select.
• Whenever user changes any value to these form fields then
the value is also updated in view model.
Note: If you’re working with checkboxes or radio buttons,
use the checked binding to read and write your element’s
checked state, not the value binding.
Example 1 Input fields:
<label>First name: <input data-bind="value: firstName"
/></label>
<label>Last Name: <input type=“number" data-bind="value:
age" ></label>
var viewModel = {
firstName : ko.observable(""),
age: ko.observable()
};
Example 2: DropDown
<p>
Select a name:
<select data-bind="options: countries,
optionsCaption: 'Choose one
value: selectedName>
</select>
</p>
var viewModel = {
names: ko.observableArray(*‘Ravinder', ‘Amit',
‘Kunal‘,’nachiket’+),
selectedName: ko.observable()
};
http://jsfiddle.net/ravindermahajan890/tbCY8/3/
“checked” binding
• Checked binding binds your checkbox/Radio button present
in your DOM to the properties present in view model.
• Whenever the checkbox/Radio Button is checked the
associated observable becomes true.
Ex1: Checkbox
<input type="checkbox" data-bind="checked: name" />
<input type="checkbox" data-bind="checked: age" />
var viewModel = {
name : ko.observable(true), age: ko.observable(false)
};
In this example the property associated with the correspondoing
DOM element will decide the Checked value of checkbox.
http://jsfiddle.net/ravindermahajan890/Bkt58/
Example 2: checkboxes bound to an array
<div>Sports we like:
<div><input type="checkbox" value=“cricket" data-
bind="checked: sports" /> Cricket</div>
<div><input type="checkbox" value=“soccer" data-
bind="checked: sports" /> Soccer</div>
<div><input type="checkbox" value=“tennis" data-
bind="checked: sports" /> Tennis</div>
</div>
var viewModel = {
sports: ko.observableArray([" cricket "," soccer "])
};
In this example the check box with value cricket and soccer will
be checked by default.
http://jsfiddle.net/ravindermahajan890/NC7pY/
Example 3: Radio buttons
<div> Sports we like:
<div><input type=“radio" name=“sportsGroup” value=“cricket"
data-bind="checked: sports" /> Cricket</div>
<div><input type=“radio" name=“sportsGroup” value=“soccer"
data-bind="checked: sports" /> Soccer</div>
<div><input type=“radio" name=“sportsGroup” value=“tennis"
data-bind="checked: sports" /> Tennis</div>
</div>
var viewModel = {
sports: ko.observable(‘cricket’)
};
In this example the radio box with value cricket will be checked
by default.
Note: We cannot have the value for the radio buttton under
single name populated from an observable array.
“selectedOptions” binding
• This binding is used in case of multi-select lists and all the the
values currently selected are put in an observable array.
Example :
<p>
Select a name:
<select data-bind="options: names,
selectedOption:selectedName”,
size=“2“, multiple="true"</select>
</p>
var viewModel = {
names: *‘Ravinder', ‘Amit',‘Kunal‘,’nachiket’+,
selectedName: ko.observableArray()
};
http://jsfiddle.net/ravindermahajan890/v5AVU/
Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
Pros and Cons of knockout
Pros:
• Light and fast, only 41kb
• Declarative two-way binding
• It lets you manipulate the CSS from the HTMl itself on the
basis of observables.
• The amount of JavaScript code to write is very less
• No dependency on any other library.
Cons:
• Jquery templates are not completely supported
• It provides only two way binding and does not support
modern concepts like Hash based Routing
Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓ Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
Examples
Simple Binding: http://jsfiddle.net/ravindermahajan890/DM67E/
Computed Binding:http://jsfiddle.net/ravindermahajan890/J8Ymw/
Subscribers:http://jsfiddle.net/ravindermahajan890/qYhTw/1/
http://jsfiddle.net/ravindermahajan890/qYhTw/2/
visible Binding: http://jsfiddle.net/ravindermahajan890/2aYXj/
Html Binding: http://jsfiddle.net/ravindermahajan890/8XW43/
CSS Binding: http://jsfiddle.net/ravindermahajan890/k7ys4/1/
Foreach Binding:http://jsfiddle.net/ravindermahajan890/mC73V/1/
If Binding:http://jsfiddle.net/ravindermahajan890/KAAxD/
With Binding: http://jsfiddle.net/ravindermahajan890/drF9L/
ContainerlessBinding: http://jsfiddle.net/ravindermahajan890/m2uVt/
Enable Binding: http://jsfiddle.net/ravindermahajan890/btZgV/
Click Binding: http://jsfiddle.net/ravindermahajan890/qWg82/1/
Select Binding: http://jsfiddle.net/ravindermahajan890/tbCY8/
Checked binding:http://jsfiddle.net/ravindermahajan890/Bkt58/
Array Bound Checked Binding:http://jsfiddle.net/ravindermahajan890/Bkt58/
MultiList Binding: http://jsfiddle.net/ravindermahajan890/v5AVU/
Thank You

Contenu connexe

Tendances

An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDBCésar Trigo
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NETDror Helper
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...Edureka!
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Introduction To WordPress
Introduction To WordPressIntroduction To WordPress
Introduction To WordPressCraig Bailey
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentGabriel Walt
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 

Tendances (20)

An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Introduction to mongodb
Introduction to mongodbIntroduction to mongodb
Introduction to mongodb
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
MongoDB
MongoDBMongoDB
MongoDB
 
Introduction To WordPress
Introduction To WordPressIntroduction To WordPress
Introduction To WordPress
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component Development
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 

En vedette

Knockout.js を利用したインタラクティブ web アプリケーション開発
Knockout.js を利用したインタラクティブ web アプリケーション開発Knockout.js を利用したインタラクティブ web アプリケーション開発
Knockout.js を利用したインタラクティブ web アプリケーション開発Daizen Ikehara
 
Knockout (support slides for presentation)
Knockout (support slides for presentation)Knockout (support slides for presentation)
Knockout (support slides for presentation)Aymeric Gaurat-Apelli
 
Introduction to Knockoutjs
Introduction to KnockoutjsIntroduction to Knockoutjs
Introduction to Knockoutjsjhoguet
 
Knockout js
Knockout jsKnockout js
Knockout jshhassann
 
An introduction to knockout.js
An introduction to knockout.jsAn introduction to knockout.js
An introduction to knockout.jsEmanuele DelBono
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentationScott Messinger
 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingUdaya Kumar
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneDeepu S Nath
 
Download presentation
Download presentationDownload presentation
Download presentationwebhostingguy
 

En vedette (20)

Knockout.js を利用したインタラクティブ web アプリケーション開発
Knockout.js を利用したインタラクティブ web アプリケーション開発Knockout.js を利用したインタラクティブ web アプリケーション開発
Knockout.js を利用したインタラクティブ web アプリケーション開発
 
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 explained
Knockout.js explainedKnockout.js explained
Knockout.js explained
 
Introduction to Knockoutjs
Introduction to KnockoutjsIntroduction to Knockoutjs
Introduction to Knockoutjs
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Knockout js
Knockout jsKnockout js
Knockout js
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
 
An introduction to knockout.js
An introduction to knockout.jsAn introduction to knockout.js
An introduction to knockout.js
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
 
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
 
Knockout js
Knockout jsKnockout js
Knockout js
 
Golang
GolangGolang
Golang
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
 
Knockout js
Knockout jsKnockout js
Knockout js
 
Download presentation
Download presentationDownload presentation
Download presentation
 

Similaire à Knockout js session

Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
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
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsAviran Cohen
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from ScratchUdaya Kumar
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 
Bringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBoyan Mihaylov
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersFrank La Vigne
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day OneTroy Miles
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting StartedMurat Doğan
 

Similaire à Knockout js session (20)

Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
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!
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS Fundamentals
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Angular js anupama
Angular js anupamaAngular js anupama
Angular js anupama
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
AngularJS.pptx
AngularJS.pptxAngularJS.pptx
AngularJS.pptx
 
Angular js
Angular jsAngular js
Angular js
 
Bringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJS
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government Developers
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
 

Dernier

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Knockout js session

  • 1. Knockout Js By Ravinder Mahajan -Synerzip
  • 2. About Me •I am Ravinder Mahajan, working as a web developer since beginning of my career. •I am microsoft certified HTML5 with JavaScript and CSS3 solution provider. • I love to explore about the latest technologies/libraries. •In free time I like to travel to different places. http://www.linkedin.com/pub/ravinder-mahajan/23/508/668
  • 3. Agenda for this session • What is knockout js? • What is MVVM? • Why to use Knockout js? • What are observables? • What are computed properties? • What are subscribers? • What are Bindings in knockout? • Pros and Cons of knockout Few Examples at the end to demonstrate the same!!!
  • 4. What is knockout? • Knockout is a JavaScript library built mainly to provide two way binding between HTML and Data(View model) and gives us a responsive display. • Two way binding HTML In sync ViewModel
  • 5. Agenda for this session ✓ What is knockout js? ✓ What is MVVM? ✓ Why to use Knockout js? ✓ What are observables? ✓ What are computed properties? ✓ What are subscribers? ✓ What are Bindings in knockout? ✓ Pros and Cons of knockout Few Examples at the end to demonstrate the same!!!
  • 6. What is MVVM? MVVM is a pattern which helps us achieve Two way binding between our HTML page and Data. • Model: The model represents the actual data and/or information we are dealing with • View: The view is something that end user really interacts with ie the HTML content • ViewModel: The viewmodel may expose the model directly, or properties related to the model, for data- binding in a formatted/Refined or presentable form. Ex: let us suppose that our Model Contains a lot of detail about employees however at the UI we only want to display Name And Age, this is something what is achieved by ViewModel
  • 8. Agenda for this session ✓What is knockout js? ✓What is MVVM? ✓Why to use Knockout js? ✓What are observables? ✓What are computed properties? ✓What are subscribers? ✓What are Bindings in knockout? Few Examples at the end to demonstrate the same!!!
  • 9. Why to use knockout • Declarative Binding: Binding View Models’ properties to HTML is very easy Eg: <span data-bind="text: myProperty"></span> • Automatic Dom refresh: Every time a property changes in View Model, its associated Dom is automatically refreshed but not the entire Page • Dependency Tracking: If a property is dependent on other property then knockout can easily detect that and can perform further operations. • Templating: Knockout provides you with its own templating engine which is quite fast, however we can also use any of our templating engines. Note: Knockout is very light weight and does not have any dependency on any other js library.
  • 10. Agenda for this session ✓ What is knockout js? ✓ What is MVVM? ✓ Why to use Knockout ? ✓ What are observables? ✓ What are computed properties? ✓ What are subscribers? ✓ What are Bindings in knockout? ✓ What are custom Bindings? Few Examples at the end to demonstrate the same!!!
  • 11. What are observables? • Observable are knockout properties which holds the Model properties needed to bind the data to the UI and internally is responsible for Two way binding. Example function MyViewModel(){ this.firstName: ko.observable(‘Ravinder’), this.lastName: ko.observable(‘Mahajan’) }; ko.applyBindings(new MyViewModel(),$(‘#personName’)); <span id=‘personName’ data-bind=“text:firstName”> // Ravinder http://jsfiddle.net/ravindermahajan890/DM67E/
  • 12. Agenda for this session ✓ What is knockout js? ✓ What is MVVM? ✓ Why to use Knockout ? ✓ What are observables? ✓ What are computed properties? ✓ What are subscribers? ✓ What are Bindings in knockout? ✓ What are custom Bindings? Few Examples at the end to demonstrate the same!!!
  • 13. What are computed Observables? • computed observables are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change. Example: function MyViewModel(){ this.firstName: ko.observable(‘Ravi’); this.lastName: ko.observable(‘Jain’); this.fullName=ko.computed(function(){ return this.firstName()+ this.lastName(); },this); }; ko.applyBindings(new MyViewModel(),$(‘#personName’)); <span id=‘personName’ data-bind=“text:fullName”> // Ravi Jain
  • 14. Case1: First Name:Ravinder Last Name:Mahajan Full Name:Ravinder Mahajan Now if we edit first and Last Name: Case2: First Name: Ankit Last Name: Kumar Full Name: Ankit Kumar http://jsfiddle.net/ravindermahajan890/J8Ymw/ Note: Full name always detect the change in First Name and Last Name by subscribing to them internally and is computed every time.
  • 15. Agenda for this session ✓ What is knockout js? ✓ What is MVVM? ✓ Why to use Knockout ? ✓ What are observables? ✓ What are computed properties? ✓ What are subscribers? ✓ What are Bindings in knockout? ✓ What are custom Bindings? Few Examples at the end to demonstrate the same!!!
  • 16. What are subscribers? • Subscriptions are registered to notify any change in the subscribed properties. Example 1: var myViewModel= new MyViewModel(); myViewModel.personName.subscribe(function(newValue) { alert(“New value is " + newValue); }); Example 2: myViewModel.personName.subscribe(function(newValue) { alert(“New value is " + newValue); },this,”beforeChange”); http://jsfiddle.net/ravindermahajan890/qYhTw/3/
  • 17. Agenda for this session ✓What is knockout js? ✓What is MVVM? ✓Why to use Knockout ? ✓What are observables? ✓What are computed properties? ✓What are subscribers? ✓What are Bindings in knockout? ✓What are custom Bindings? Few Examples at the end to demonstrate the same!!!
  • 18. What are Bindings in knockout? Binding is a phenomenon where in we actually bind the data present in ViewModels to our HTML page using some pre-defined keyword(s) well understood by Knockout Different types of Binding are available: 1. Text , HTML and appearance Bindings 2. Control flow Bindings 3. Form fields Bindings 4. Custom Binding(To be covered Later)
  • 19. 1) Text , HTML and appearance Bindings • visible binding: Visible binding causes the Dom Element to switch is visiblity property on the basis of associated Knockout Property. Example: <div data-bind="visible: visiblePropertyName"> You will see this message only when " visiblePropertyName " holds a true value. </div> var viewModel = { visiblePropertyName : ko.observable(true) }; viewModel. visiblePropertyName (false);//This div will not be visible anymore http://jsfiddle.net/ravindermahajan890/2aYXj/
  • 20. • Text binding: Text binding causes the associated DOM element to display the text value of associated property. We can use it with almost all the elements. Example 1: <span data-bind="text: myMessage , visible:myMessage()!=null "></span> var viewModel = { myMessage: ko.observable(null) , count:ko.observable(10) }; viewModel.myMessage(“Welcome to the world of knockout!"); Text Binding
  • 22. HTML Binding • HTML binding first converts the string into its corresponding HTML value and then binds the data to it. • The HTML binding causes the associated DOM element to display the HTML specified by your parameter. Example: <div data-bind="html: details"></div> var viewModel = { details: ko.observable() }; viewModel.details("<em>welcome to <i>Synerzip</i></em>"); Output: “welcome to Synerzip”
  • 23. Note: It is always preferred to use text binding as it removes the problem of script inection or if we are using HTML binding, make sure we encode the text first. http://jsfiddle.net/ravindermahajan890/8XW43/
  • 24. CSS Binding The css binding adds or removes one or more named CSS classes to the associated DOM element. Example 1: <div data-bind="css: { profitWarning: currentProfit() < 0 }"> Profit Information </div> In this example if the currentProfit() evaluates to less than 0 then the profit warning css would be applied to the Div. CSS Expression
  • 25. Example 2: <div data-bind="css: { profitWarning: currentProfit() < 0, major highlight: isSevere }"> This example explains that how can we switch between css classes on the basis of our conditions. http://jsfiddle.net/ravindermahajan890/k7ys4/1/
  • 26. Style Binding The style binding adds or removes one or more style values to the associated DOM element Example: <div data-bind="style: { color: age() < 0 ? 'red' : 'black' }"> Profit Information </div> var viewModel = { age: ko.observable(15) }; viewModel.age(-50); In this example the color value would change its property on the basis of the age() condition.
  • 27. Attr Binding The attr binding ia a way to set the value of any attribute for the associated DOM element. It is useful, when we want to assign any attribute on the basis of our viewModels( mainly “src” of an img tag, or the “href” of a link based on values in your view model, title of any element) <a data-bind="attr: { href: url, title: details }"> Synerzip </a> var viewModel = { url: ko.observable(“synerzip.html"), details: ko.observable(“Welcome to Synerzip") };
  • 28. 2) Control Flow Bindings Control Flow Bindings are the bindings which control the flow of application Different types of Control Flow Binding are: • Foreach Binding • If Binding • Ifnot Binding • With Binding Note: ”ifnot” binding is as good as negated if binding so we will not touch on ifnot binding
  • 29. foreach Binding The foreach binding is generally used to render list or tables where in the value/Properties is an observable array. Example: <div data-bind="foreach: people"> <div data-bind="text: name"></div> </div> var viewModel = { people: ko.observableArray([{ name: 'Bert' },{ name: 'Charles' }, { name: 'Denise' }]) }; Output: Bert Charles Denise http://jsfiddle.net/ravindermahajan890/mC73V/1/
  • 30. If Binding The if binding causes your HTML element in your document only if a specified expression evaluates to true/Non null object. Example 1: <div data-bind="if: displayMessage"> <span>My content<span> </div> var viewModel={ displayMessage: ko.observable(false) }; In the above example the div would not take any space in the DOM and would not be rendered
  • 31. Example 2: <div data-bind="if: displayMessage"> <span>My content<span> </div> var viewModel={ displayMessage: ko.observable(true) }; I would be able to see My content on the page as the displayMessage property evaluates to true http://jsfiddle.net/ravindermahajan890/KAAxD/
  • 32. Note: If binding is somewhat similar to visible binding however the difference is that with “visible” binding the HTML always remains in the Dom and which at time becomes overhead but in the case of “if” binding the element is rendered when the condition evaluates to true and applies bindings to its descendants only when the “if” binding evaluates to true.
  • 33. with binding “The with binding creates a new binding context, so that descendant elements are bound in the context of a specified object” Ex1: <div data-bind="with: name“> <span data-bind="text: firstName"> </span>//name.firstName <span data-bind="text: lastName"> </span>//name.lastName </div> var viewModel={ name: { firstName: ’Ravinder’, lastName: ‘Mahajan’ } }); http://jsfiddle.net/ravindermahajan890/drF9L/
  • 34. Container less Binding In Container less binding the binding can be easily achieved without using a container element. Example 1: <!-- ko foreach: people --> <div data-bind="text: name"></div> <!-- /ko --> Example 2: <!-- ko if: displayMessage --> <span>My content<span> <!-- /ko -->
  • 35. Example 3: <!-- ko with: name> <span data-bind="text: firstName"> </span>//name.firstName <span data-bind="text: lastName"> </span>//name.lastName <!-- /ko --> http://jsfiddle.net/ravindermahajan890/m2uVt/
  • 36. 3) Form Fields Binding These are the bindings which are used while working with Form fields. Different types of Form field bindings are: • "click" binding • “event” binding • “submit” binding • “enable” binding • “value” binding • “checked” binding • “options” binding • "selectedOptions" binding
  • 37. "click" binding • The click binding adds an event handler so that your chosen JavaScript function will be invoked when the associated DOM element is clicked Example 1: <div>You've clicked <span data-bind="text: numberOfClicks"></span> times <button data-bind="click: incrementClickCounter">Click me</button> </div> var viewModel = { numberOfClicks : ko.observable(), incrementClickCounter : function(data,event) { var previousCount = this.numberOfClicks(); this.numberOfClicks(previousCount + 1); }}; In this example clicking on the button would increment the this.numberOfClicks by1.
  • 38. “submit” binding Submit binding is very much similar to click binding on button, submit binding prevents the default submit action and will call your method instead. However, submit has the advantage that it also captures alternative ways to submit the form, such as pressing the enter key while typing into a text box. http://jsfiddle.net/ravindermahajan890/qWg82/2/
  • 39. “enable” binding • The enable binding causes the Dom element to be enabled or disabled on the basis of observable property Example 1: <input type=“text” data-bind='enable: name()!=‘null’,value: name"> click to enable </input> var viewModel = { this.name: ko.observable(null) }; http://jsfiddle.net/ravindermahajan890/qWg82/2/
  • 40. “value” binding • Value binding binds your elements present in your DOM to the properties present in view model. • They are mainly used with form fields such as Input , Select. • Whenever user changes any value to these form fields then the value is also updated in view model. Note: If you’re working with checkboxes or radio buttons, use the checked binding to read and write your element’s checked state, not the value binding.
  • 41. Example 1 Input fields: <label>First name: <input data-bind="value: firstName" /></label> <label>Last Name: <input type=“number" data-bind="value: age" ></label> var viewModel = { firstName : ko.observable(""), age: ko.observable() };
  • 42. Example 2: DropDown <p> Select a name: <select data-bind="options: countries, optionsCaption: 'Choose one value: selectedName> </select> </p> var viewModel = { names: ko.observableArray(*‘Ravinder', ‘Amit', ‘Kunal‘,’nachiket’+), selectedName: ko.observable() }; http://jsfiddle.net/ravindermahajan890/tbCY8/3/
  • 43. “checked” binding • Checked binding binds your checkbox/Radio button present in your DOM to the properties present in view model. • Whenever the checkbox/Radio Button is checked the associated observable becomes true. Ex1: Checkbox <input type="checkbox" data-bind="checked: name" /> <input type="checkbox" data-bind="checked: age" /> var viewModel = { name : ko.observable(true), age: ko.observable(false) }; In this example the property associated with the correspondoing DOM element will decide the Checked value of checkbox. http://jsfiddle.net/ravindermahajan890/Bkt58/
  • 44. Example 2: checkboxes bound to an array <div>Sports we like: <div><input type="checkbox" value=“cricket" data- bind="checked: sports" /> Cricket</div> <div><input type="checkbox" value=“soccer" data- bind="checked: sports" /> Soccer</div> <div><input type="checkbox" value=“tennis" data- bind="checked: sports" /> Tennis</div> </div> var viewModel = { sports: ko.observableArray([" cricket "," soccer "]) }; In this example the check box with value cricket and soccer will be checked by default. http://jsfiddle.net/ravindermahajan890/NC7pY/
  • 45. Example 3: Radio buttons <div> Sports we like: <div><input type=“radio" name=“sportsGroup” value=“cricket" data-bind="checked: sports" /> Cricket</div> <div><input type=“radio" name=“sportsGroup” value=“soccer" data-bind="checked: sports" /> Soccer</div> <div><input type=“radio" name=“sportsGroup” value=“tennis" data-bind="checked: sports" /> Tennis</div> </div> var viewModel = { sports: ko.observable(‘cricket’) }; In this example the radio box with value cricket will be checked by default. Note: We cannot have the value for the radio buttton under single name populated from an observable array.
  • 46. “selectedOptions” binding • This binding is used in case of multi-select lists and all the the values currently selected are put in an observable array. Example : <p> Select a name: <select data-bind="options: names, selectedOption:selectedName”, size=“2“, multiple="true"</select> </p> var viewModel = { names: *‘Ravinder', ‘Amit',‘Kunal‘,’nachiket’+, selectedName: ko.observableArray() }; http://jsfiddle.net/ravindermahajan890/v5AVU/
  • 47. Agenda for this session ✓What is knockout js? ✓What is MVVM? ✓Why to use Knockout ? ✓What are observables? ✓What are computed properties? ✓What are subscribers? ✓What are Bindings in knockout? ✓Pros and Cons of knockout Few Examples at the end to demonstrate the same!!!
  • 48. Pros and Cons of knockout Pros: • Light and fast, only 41kb • Declarative two-way binding • It lets you manipulate the CSS from the HTMl itself on the basis of observables. • The amount of JavaScript code to write is very less • No dependency on any other library. Cons: • Jquery templates are not completely supported • It provides only two way binding and does not support modern concepts like Hash based Routing
  • 49. Agenda for this session ✓What is knockout js? ✓What is MVVM? ✓Why to use Knockout ? ✓What are observables? ✓What are computed properties? ✓What are subscribers? ✓What are Bindings in knockout? ✓ Pros and Cons of knockout Few Examples at the end to demonstrate the same!!!
  • 50. Examples Simple Binding: http://jsfiddle.net/ravindermahajan890/DM67E/ Computed Binding:http://jsfiddle.net/ravindermahajan890/J8Ymw/ Subscribers:http://jsfiddle.net/ravindermahajan890/qYhTw/1/ http://jsfiddle.net/ravindermahajan890/qYhTw/2/ visible Binding: http://jsfiddle.net/ravindermahajan890/2aYXj/ Html Binding: http://jsfiddle.net/ravindermahajan890/8XW43/ CSS Binding: http://jsfiddle.net/ravindermahajan890/k7ys4/1/ Foreach Binding:http://jsfiddle.net/ravindermahajan890/mC73V/1/ If Binding:http://jsfiddle.net/ravindermahajan890/KAAxD/ With Binding: http://jsfiddle.net/ravindermahajan890/drF9L/ ContainerlessBinding: http://jsfiddle.net/ravindermahajan890/m2uVt/ Enable Binding: http://jsfiddle.net/ravindermahajan890/btZgV/ Click Binding: http://jsfiddle.net/ravindermahajan890/qWg82/1/ Select Binding: http://jsfiddle.net/ravindermahajan890/tbCY8/ Checked binding:http://jsfiddle.net/ravindermahajan890/Bkt58/ Array Bound Checked Binding:http://jsfiddle.net/ravindermahajan890/Bkt58/ MultiList Binding: http://jsfiddle.net/ravindermahajan890/v5AVU/