Knockout js session

51
Knockout Js By Ravinder Mahajan -Synerzip

description

This is a presentation on the basics of knockout js.

Transcript of Knockout js session

Page 1: Knockout js session

Knockout Js

By Ravinder Mahajan

-Synerzip

Page 2: Knockout js session

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

Page 3: Knockout js session

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!!!

Page 4: Knockout js session

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

Page 5: Knockout js session

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!!!

Page 6: Knockout js session

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

Page 7: Knockout js session

Model(Service/DB directly)

View Model

HTML

Page 8: Knockout js session

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!!!

Page 9: Knockout js session

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.

Page 10: Knockout js session

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!!!

Page 11: Knockout js session

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/

Page 12: Knockout js session

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!!!

Page 13: Knockout js session

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

Page 14: Knockout js session

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.

Page 15: Knockout js session

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!!!

Page 16: Knockout js session

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/

Page 17: Knockout js session

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!!!

Page 18: Knockout js session

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)

Page 19: Knockout js session

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/

Page 20: Knockout js session

• 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

Page 21: Knockout js session

Example 2: <span data-bind="text: count()>10?’Ravinder’:’Synerzip’,visible:myMessage()!=null "> </span> http://jsfiddle.net/ravindermahajan890/2aYXj/

Page 22: Knockout js session

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”

Page 23: Knockout js session

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/

Page 24: Knockout js session

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

Page 25: Knockout js session

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/

Page 26: Knockout js session

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.

Page 27: Knockout js session

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")

};

Page 28: Knockout js session

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

Page 29: Knockout js session

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/

Page 30: Knockout js session

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

Page 31: Knockout js session

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/

Page 32: Knockout js session

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.

Page 33: Knockout js session

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/

Page 34: Knockout js session

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 -->

Page 35: Knockout js session

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/

Page 36: Knockout js session

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

Page 37: Knockout js session

"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.

Page 38: Knockout js session

“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/

Page 39: Knockout js session

“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/

Page 40: Knockout js session

“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.

Page 41: Knockout js session

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()

};

Page 42: Knockout js session

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/

Page 43: Knockout js session

“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/

Page 44: Knockout js session

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/

Page 45: Knockout js session

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.

Page 46: Knockout js session

“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/

Page 47: Knockout js session

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!!!

Page 48: Knockout js session

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

Page 49: Knockout js session

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!!!

Page 50: Knockout js session

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/

Page 51: Knockout js session

Thank You