Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Knockout JS

Ganesan Chandrasekaran
Chapter I
INTRODUCTION

11/16/2019 HCL Technologies 2


What is Knockout JS ?
 KnockoutJS is basically a library written in JavaScript that is based on MVVM
(Model-View-ViewModel) pattern that helps developers building rich and
responsive websites. This separates the application's Model (stored data), View (UI)
and View Model (Javascript Representation of model).
 Basic understanding of HTML, CSS, JavaScript, Document Object Model (DOM)
and any text editor.
 KnockoutJS was developed and is maintained as an open source project bySteve
Sanderson, a Microsoft employee on July5, 2010.

11/16/2019 HCL Technologies 3


Features of Knockout JS
 Declarative Binding
o HTML DOM elements are connected to model through data-bind attribute using very
simple syntax. It is made easy to achieve responsiveness using this feature.
 Automatic UI Refresh
o Any changes made to view model data are reflected in UI automatically and vice-versa.
No need of writing extra code for this.
 Dependency Tracking
o Relationship between KO attributes and KO library functions/components is
transparent. Automatically tracks data changes in KO attribute and update respective
affected areas.
 Templating
o Templates are a simple and convenient way to build complex UI structures - with
possibility of repeating or nesting blocks - as a function of view model data.
 Extensible
o Extends custom behavior very easily.

11/16/2019 HCL Technologies 4


Why do we need Knockout JS
 KnockoutJS library provides an easy and clean way to handle complex data-driven
interfaces. One can create self-updating UIs for JavaScript objects.
 It is pure JavaScript Library and works with any web framework. It's not a
replacement of jQuery but can work as supplement providing smart features.
 KnockoutJS library file is very small & lightweight.
 KnockoutJS is independent of any other framework. And is compatible with other
client or server side technologies.
 Most important of all KnockoutJS is open source and hence free for use.
 KnockoutJS is fully documented. The official site has full documentation including
API docs, live examples and interactive tutorials.
 KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari
(desktop/mobile).

11/16/2019 HCL Technologies 5


How to include in the project
 KO is nothing but a JavaScript Library.

 The following line will explain how to include in the HTML project
• <script type='text/javascript' src='knockout-3.4.0.js'></script>

 We can refer to the KnockoutJS library from CDNs


• <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>

• <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type="text/javascript"></script>

11/16/2019 HCL Technologies 6


Architecture of KO
 View
o View is nothing but User Interface
created using HTML elements and
CSS styling.
 ViewModel
o ViewModel is a Javascript object
which contains necessary properties
and functions to represent data. View
and ViewModel are connected
together with declarative data-bind
concept used in HTML.
 Model
o Model is domain data on server and it
gets manipulated as and when request
is sent/received from ViewModel.

11/16/2019 HCL Technologies 7


Model-View-ViewModel
 It is an architectural design pattern for
developing software applications.
MVVM was developed by Microsoft
Architect John Gossman in 2005. This
pattern is derived from Model-View-
Controller (MVC) pattern.
 The advantage of MVVM is that it
separates application layer's graphical
user interface from business logic.
MVVM is responsible for handling
data from underlying model in such a
way that it is represented and
managed very easily.
 ViewModel in MVVM represents
abstract version of View's state and
actions.
11/16/2019 HCL Technologies 8
Cont.
 A model: It is application’s stored data. This data represents objects and operations in our
business domain (e.g., bank accounts that can perform money transfers) and is
independent of any UI.
• When using KO, we will usually make Ajax calls to some server-side code to read and write this stored
model data.
 A view model: a pure-code representation of the data and operations on a UI. For
example, if we’re implementing a list editor, our view model would be an object holding
a list of items, and exposing methods to add and remove items.
• Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the
persisted data model either - it holds the unsaved data the user is working with. When using KO, our
view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model
abstract in this way lets it stay simple, so we can manage more sophisticated behaviors without getting
lost.
 A view: a visible, interactive UI representing the state of the view model. It displays
information from the view model, sends commands to the view model (e.g., when the
user clicks buttons), and updates whenever the state of the view model changes.
• When using KO, our view is simply our HTML document with declarative bindings to link it to the view
model. Alternatively, we can use templates that generate HTML using data from our view model.

11/16/2019 HCL Technologies 9


Can we have only one ViewModel?
 No. But by traditionally the programmers use one ViewModel. It is permitted to have
‘n’ number of ViewModels.
 The following explains this,
o To create a view model with KO, just declare any JavaScript object.
• var myViewModel = { personName: 'Bob', personAge: 123 };
o We can then create a very simple view of this view model using a declarative binding.
• The name is <span data-bind="text: personName"></span>
o To activate Knockout, add the following line to a <script> block:
• ko.applyBindings(myViewModel);
 ko.applyBindings takes one mandatory and one optional parameters
o The first parameter says what view model object we want to use with the declarative bindings
it activates
o Optionally, we can pass a second parameter to define which part of the document we want to
search for data-bind attributes.
• For example, ko.applyBindings(myViewModel, document.getElementById('someElementId')).
o This restricts the activation to the element with ID someElementId and its descendants, which
is useful if we want to have multiple view models and associate each with a different region of
the page.

11/16/2019 HCL Technologies 10


An Sample Code using
KO
The view classes do not know that
Model and ViewModel classes
exists, also Model and ViewModel
does not know that View exists.
Model is also unaware that
ViewModel and View exists.

11/16/2019 HCL Technologies 11


Chapter II
BASIC OF KO

11/16/2019 HCL Technologies 12


Observables
 As the name specifies, when we declare a ViewModel data/property as
Observable, any modification done every time to that data is automatically
reflected to all places wherever it is used.
 This also includes refreshing related dependencies. KO takes care of these things
and we don't have to write any extra code to achieve this.
• this.property = ko.observable('value');
 Data modification can take place either from UI or from ViewModel. Irrespective of
from where data is changed, UI and ViewModel keep synchronization among
them. This makes it two-way-binding mechanism

11/16/2019 HCL Technologies 13


Observable Arrays
 Observable declaration takes care of data-modifications of single object.
ObservableArray works with collection of objects.
 This is very useful feature when we are dealing with complex applications
containing multiple type of values and changing their status frequently based on
user actions.
• this.arrayName = ko.observableArray();
o Observable array only tracks which objects in it are added or removed. It does not notify
if individual object's properties are modified.
 We can initialize our array at the same time we declare it as Observable by passing
initial values to constructor as below
• this.arrayName = ko.observableArray([‘Square’, ‘Circle’]);
 We can access Observable array elements as below
• alert('The second element is ' + arrayName()[1]);

11/16/2019 HCL Technologies 14


ObservableArray Functions
 KnockoutJS has got its own set of Observable array functions. Those are convenient
because
o These functions works on all browsers.
o These functions will take care of dependency tracking automatically.
o Syntax is easy to use. For example to insert an element into array we just need to
use arrayName.push('value') instead ofarrayName().push('value').
 Some functions:
o push('value')
o unshift('value')
o splice(start-index, end-index)
o removeAll()
o remove([set of values])

11/16/2019 HCL Technologies 15


Computed Observables
 Computed Observable is a function
which is dependent on one or more
Observables and will automatically
update whenever its underlying
Observables (dependencies) change.
 Computed Observables can be
chained.
• this.varName=ko.computed(function()
{ ...

...

// function code

...

}, this);

11/16/2019 HCL Technologies 16


Declarative Bindings
 Declarative binding in KnockoutJS provides a powerful way to connect data to UI.
 It is important to understand relationship between bindings and Observables.
Technically these two are different. We can use normal JavaScript object as
ViewModel and KnockoutJS can process View's binding correctly.
 Without Observable the property from UI will be processed only for the first time.
In this case it cannot update automatically based on underlying data update. To
achieve this, bindings must be referred to Observable properties.
 The binding consist of 2 items, the binding name and value.
• Today is : <span data-bind="text: whatDay"></span>
• Your name: <input data-bind="value: yourName, valueUpdate: 'afterkeydown'" />
 The binding value can be a single value, literal, a variable or can be a JavaScript
expression. If binding refers to some invalid expression or reference, then KO will
output an error and stop processing the binding.

11/16/2019 HCL Technologies 17


Dependency Tracking
 KnockoutJs automatically tracks the
dependencies when the values get
updated. It has a single object called
dependency tracker
(ko.dependencyDetection) which acts as
an intermediate between two parties for
subscribing the dependencies. The logic
is being given in the image.
 Whenever we declare a computed
observable, KO immediately invokes its
evaluator function to get its initial value.
 Subscription is set up to any observable
that evaluator reads.
 KO finally notifies the updated
computed observable.

11/16/2019 HCL Technologies 18


Templating
 Template is a set of DOM elements which can be used repetitively. Templating
makes it easy to build complex applications due to its property of minimizing
duplication of DOM elements.
 There are 2 ways of creating templates:
o Native templating- This method supports control flow bindings like foreach, with and if.
These bindings capture HTML markup existing in the element and use it as template for
random items. No external library is required for this templating.
o String-based templating- KO connects to third party engine to pass ViewModel values
into it and injects resulting markup into document. E.g. JQuery.tmpl and Underscore
Engine.
template: <parameter-value>
<script type="text/html" id="template-name">
...
... // DOM elements to be processed ...
</script>

11/16/2019 HCL Technologies 19


Components
 Components are a huge way of organizing the UI code for structuring a large
application and promote code reusability.
o It is inherited or nested from other component.
o For loading and configuration, it defines its own conventions or logic.
o It is packaged to reuse throughout the application or project.
o Represents the complete sections of application or small controls/widgets.
o Loaded or preloaded on demand.

ko.components.register('component-name', {
viewModel: {...}, //function code
template: {....) //function code
});

11/16/2019 HCL Technologies 20


Chapter III
OBSERVABLES

11/16/2019 HCL Technologies 21


Why Observables?
 One of the key benefits of KO is that it updates our UI automatically when the view
model changes. How can KO know when parts of our view model
change? Answer: Observables
 We need to declare our model properties as observables, because these are special
JavaScript objects that can notify subscribers about changes, and can automatically
detect dependencies.
 Not all browsers support JavaScript getters and setters, so for compatibility,
ko.observable objects are actually functions.

11/16/2019 HCL Technologies 22


Reading and Writing Observable
 We can read write via Observable, even multiple writing is possible
o To read the observable’s current value, just call the observable with no parameters.
• myViewModel.personName()
o To write a new value to the observable, call the observable and pass the new value as a
parameter.
• myViewModel.personName('Mary')
o To write values to multiple observable properties on a model object, we can use chaining
syntax.
• myViewModel.personName('Mary').personAge(50)
 We can explicitly subscribe to observables
 When writing to an observable that contains a primitive value (a number, string,
boolean, or null), the dependencies of the observable are normally only notified if
the value actually changed. However, it is possible to use the built-
in notify extender to ensure that an observable’s subscribers are always notified on
a write, even if the value is the same.
• myViewModel.personName.extend({ notify: 'always' });

11/16/2019 HCL Technologies 23


Observable Arrays
 To detect and respond to changes on one object, we’d use observable.
 To detect and respond to changes of a collection of things, use an observableArray.
• var myObservableArray = ko.observableArray(); // Initially an empty array
• myObservableArray.push('Some value'); // Adds the value and notifies observers
 An observableArray tracks which objects are in the array, not the state of those objects
o Simply putting an object into an observableArray doesn’t make all of that object’s properties
themselves observable. But that too is possible.
o An observableArray just tracks which objects it holds, and notifies listeners when objects are
added or removed.
 Prepopulating an observableArray:
o If we want our observable array not to start empty, but to contain some initial items, pass those
items as an array to the constructor.
var anotherObservableArray = ko.observableArray([
{ name: "Bungle", type: "Bear" },
{ name: "George", type: "Hippo" },
{ name: "Zippy", type: "Unknown" }
]);

11/16/2019 HCL Technologies 24


Cont.
 Reading information from an observableArray
• alert('The length of the array is ' + myObservableArray().length);
• alert('The first element is ' + myObservableArray()[0]);
 Technically we can use any of the native JavaScript array functions to operate on
that underlying array, but normally there’s a better alternative.
KO’s observableArray has equivalent functions of its own.
o They work on all targeted browsers.
o Automatically trigger the dependency tracking mechanism so that all registered listeners
are notified of the change, and UI is automatically updated.
o The syntax is more convenient.

11/16/2019 HCL Technologies 25


observableArray’s functions
 indexOf:
• The indexOf function returns the index of the first array item that equals our parameter. For example,
myObservableArray.indexOf('Bus') will return the zero-based index of the first array entry that equals Bus, or the value -1 if
no matching value was found.
 slice
• The slice function is the observableArray equivalent of the native JavaScript slice function
 push( value ) — Adds a new item to the end of array.
 pop() — Removes the last value from the array and returns it.
 unshift( value ) — Inserts a new item at the beginning of the array.
 shift() — Removes the first value from the array and returns it.
 reverse() — Reverses the order of the array and returns the observableArray (not the underlying array).
 sort() — Sorts the array contents and returns the observableArray.
o The default sort is alphabetical, but we can optionally pass a function to control how the array should be sorted. Our
function should accept any two objects from the array and return a negative value if the first argument is smaller, a
positive value is the second is smaller, or zero to treat them as equal.
o For example, to sort an array of ‘person’ objects by last name, we could write myObservableArray.sort(function (left,
right) { return left.lastName == right.lastName ? 0 : (left.lastName < right.lastName ? -1 : 1) })
 splice() — Removes and returns a given number of elements starting from a given index. For
example, myObservableArray.splice(1, 3) removes three elements starting from index position 1 (i.e., the
2nd, 3rd, and 4th elements) and returns them as an array.

11/16/2019 HCL Technologies 26


Cont.
 observableArray adds some more useful methods that aren’t found on JavaScript
arrays by default:
o remove( someItem ) — Removes all values that equal someItem and returns them as an
array.
o remove( function (item) { return item.age < 18; } ) — Removes all values whose age
property is less than 18, and returns them as an array.
o removeAll( ['Chad', 132, undefined] ) — Removes all values that equal 'Chad', 123, or
undefined and returns them as an array.
o removeAll() — Removes all values and returns them as an array.

11/16/2019 HCL Technologies 27


Computed observables
 These are functions that are dependent on one or more other observables, and will
automatically update whenever any of these dependencies change.
 We can create whole chains of computed observables if we wish.
o an observable called items representing a set of items
o another observable called selectedIndexes storing which item indexes have been
‘selected’ by the user
o a computed observable called selectedItems that returns an array of item objects
corresponding to the selected indexes
o another computed observable that returns true or false depending on whether any
ofselectedItems has some property (like being new or being unsaved). Some UI element,
like a button, might be enabled or disabled based on this value.
 We can manage ‘this’ as follows,
• var self = this;

11/16/2019 HCL Technologies 28


Pure computed observables
 If our computed observable simply calculates and returns a value based on some
observable dependencies, then it’s better to declare it as a ko.pureComputed instead of
a ko.computed.
this.fullName = ko.pureComputed(function() {
return this.firstName() + " " + this.lastName();
}, this);
o Since this computed is declared to be pure (i.e., its evaluator does not directly modify other
objects or state), Knockout can more efficiently manage its re-evaluation and memory use.
Knockout will automatically suspend or release it if no other code has an active dependency on
it.
• Pure computeds were introduced in Knockout 3.2.0
 When a computed observable returns a primitive value (a number, string, boolean, or
null), the dependencies of the observable are normally only notified if the value actually
changed. However, it is possible to use the built-in notify extender to ensure that a
computed observable’s subscribers are always notified on an update, even if the value is
the same.
myViewModel.fullName = ko.pureComputed(function() {
return myViewModel.firstName() + " " + myViewModel.lastName();
}).extend({ notify: 'always' });

11/16/2019 HCL Technologies 29


Cont.
 Delaying and/or suppressing change notifications
o Normally, a computed observable updates and notifies its subscribers immediately, as soon as its
dependencies change. But if a computed observable has many dependencies or involves expensive
updates, we may get better performance by limiting or delaying the computed observable’s updates
and notifications. This is accomplished using the rateLimit extender.
• myViewModel.fullName.extend({ rateLimit: 50 });
 Determining if a property is a computed observable
o In some scenarios, it is useful to programmatically determine if we are dealing with a computed
observable. Knockout provides a utility function, ko.isComputed to help with this situation.
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop) && !ko.isComputed(myObject[prop])) {
result[prop] = myObject[prop];
}
}
 Knockout provides similar functions that can operate on observables and computed observables:
• ko.isObservable - returns true for observables, observable arrays, and all computed observables.
• ko.isWritableObservable - returns true for observables, observable arrays, and writable computed observables
(also aliased as ko.isWriteableObservable).

11/16/2019 HCL Technologies 30


Cont.
 ko.computed( evaluator [, targetObject, options] )
o This form supports the most common case of creating a computed observable.
• evaluator — A function that is used to evaluate the computed observable’s current value.
• targetObject — If given, defines the value of this whenever KO invokes our callback functions. See the section on
managing this for more information.
• options — An object with further properties for the computed observable. See the full list below.
 ko.computed( options )
o This single parameter form for creating a computed observable accepts a JavaScript object with any of
the following properties.
• read — Required. A function that is used to evaluate the computed observable’s current value.
• write — Optional. If given, makes the computed observable writable. This is a function that receives values that
other code is trying to write to our computed observable.
• owner — Optional. If given, defines the value of this whenever KO invokes our read or write callbacks.
• pure — Optional. If this option is true, the computed observable will be set up as a pure computed observable.
This option is an alternative to the ko.pureComputed constructor.
• deferEvaluation — Optional. If this option is true, then the value of the computed observable will not be
evaluated until something actually attempts to access its value or manually subscribes to it. By default, a
computed observable has its value determined immediately during creation.
• disposeWhen — Optional. If given, this function is executed before each re-evaluation to determine if the
computed observable should be disposed. A true-ish result will trigger disposal of the computed observable.
• disposeWhenNodeIsRemoved — Optional. If given, disposal of the computed observable will be triggered when
the specified DOM node is removed by KO. This feature is used to dispose computed observables used in
bindings when nodes are removed by the template and control-flow bindings.

11/16/2019 HCL Technologies 31


Cont.
 Using a computed observable
o A computed observable provides the following functions:
• dispose() — Manually disposes the computed observable, clearing all subscriptions to
dependencies. This function is useful if we want to stop a computed observable from being
updated or want to clean up memory for a computed observable that has dependencies on
observables that won’t be cleaned.
• extend(extenders) — Applies the given extenders to the computed observable.
• getDependenciesCount() — Returns the current number of dependencies of the computed
observable.
• getSubscriptionsCount( [event] ) — Returns the current number of subscriptions (either from
other computed observables or manual subscriptions) of the computed observable. Optionally,
pass an event name (like "change") to return just the count of subscriptions for that event.
• isActive() — Returns whether the computed observable may be updated in the future. A
computed observable is inactive if it has no dependencies.
• peek() — Returns the current value of the computed observable without creating a dependency.
• subscribe( callback [,callbackTarget, event] ) — Registers a manual subscription to be notified of
changes to the computed observable.

11/16/2019 HCL Technologies 32


Cont.
 Determining the observable type
o To check if a property is observable, computed, etc., use the following set of functions
• ko.isObservable — returns true for observables, observable arrays, and all computed observables.
• ko.isWritableObservable — returns true for observables, observable arrays, and writablecomputed
observables (also aliased as ko.isWriteableObservable).
• ko.isComputed — returns true for all computed observables.
• ko.isPureComputed — returns true for pure computed observables.
 Using the computed context
o During the execution of a computed observable’s evaluator function, we can
accessko.computedContext to get information about the current computed property. It
provides the following functions:
• isInitial() — A function that returns true if called during the first ever evaluation of the current
computed observable, or false otherwise. For pure computed observables, isInitial() is always undefined.
• getDependenciesCount() — Returns the number of dependencies of the computed observable detected
so far during the current evaluation.
o Note: ko.computedContext.getDependenciesCount() is equivalent to callinggetDependenciesCount() on the
computed observable itself. The reason that it also exists on ko.computedContext is to provide a way of counting the
dependencies during the first ever evaluation, before the computed observable has even finished being constructed.

11/16/2019 HCL Technologies 33


Chapter IV
BINDINGS

11/16/2019 HCL Technologies 34


Various Bindings
 The visible binding

 The text binding

 The HTML binding

 The CSS binding

 The style binding

 The attr binding

11/16/2019 HCL Technologies 35


The "visible" binding
 he visible binding causes the associated DOM element to become hidden or visible
according to the value we pass to the binding.
<div data-bind="visible: shouldShowMessage">
we will see this message only when "shouldShowMessage" holds a true value.
</div>

<script type="text/javascript">
var viewModel = {
shouldShowMessage: ko.observable(true) // Message initially visible
};
viewModel.shouldShowMessage(false); // ... now it's hidden
viewModel.shouldShowMessage(true); // ... now it's visible again
</script>

11/16/2019 HCL Technologies 36


Cont.
 Parameters
o Main parameter

• When the parameter resolves to a false-like value (e.g., the boolean value false, or the numeric value 0, or
null, or undefined), the binding sets yourElement.style.display to none, causing it to be hidden. This
takes priority over any display style you’ve defined using CSS.

• When the parameter resolves to a true-like value (e.g., the boolean value true, or a non-null object or
array), the binding removes the yourElement.style.display value, causing it to become visible.

• Note that any display style you’ve configured using our CSS rules will then apply (so CSS rules like x {
display:table-row } work fine in conjunction with this binding).

o If this parameter is an observable value, the binding will update the element’s visibility
whenever the value changes. If the parameter isn’t observable, it will only set the element’s
visibility once and will not update it again later.

o Additional parameters
• None

11/16/2019 HCL Technologies 37


The "text" binding.
 The text binding causes the associated DOM element to display the text value of
our parameter. Typically this is useful with elements like <span> or <em> that
traditionally display text, but technically we can use it with any element.

Today's message is: <span data-bind="text: myMessage"></span>

<script type="text/javascript">
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
</script>

11/16/2019 HCL Technologies 38


Cont.
 Parameters
o Main parameter
• Knockout sets the element’s content to a text node with our parameter value. Any previous content will
be overwritten.
• If this parameter is an observable value, the binding will update the element’s text whenever the value
changes. If the parameter isn’t observable, it will only set the element’s text once and will not update it
again later.
• If we supply something other than a number or a string (e.g., we pass an object or an array), the
displayed text will be equivalent to yourParameter.toString()
o Additional parameters
• None
 We can use functions and expressions to detemine text values
• return this.price() > 50 ? "expensive" : "affordable";
• The item is <span data-bind="text: price() > 50 ? 'expensive' : 'affordable'"></span> today.
 Since this binding sets our text value using a text node, it’s safe to set any string value
without risking HTML or script injection.
 “text” without a container element

11/16/2019 HCL Technologies 39


The "html" binding
 The html binding causes the associated DOM element to display the HTML
specified by your parameter. Typically this is useful when values in your view
model are actually strings of HTML markup that you want to render.
<div data-bind="html: details"></div>

<script type="text/javascript">
var viewModel = {
details: ko.observable() // Initially blank
};
viewModel.details("<em>For further details, view the report <a
href='report.html'>here</a>.</em>"); // HTML content appears
</script>

11/16/2019 HCL Technologies 40


Cont.
 Parameters
o Main parameter
• KO clears the previous content and then sets the element’s content to your parameter value using
jQuery’s html function or by parsing the string into HTML nodes and appending each node as a child of
the element, if jQuery is not available.
• If this parameter is an observable value, the binding will update the element’s content whenever the
value changes. If the parameter isn’t observable, it will only set the element’s content once and will not
update it again later.
• If you supply something other than a number or a string (e.g., you pass an object or an array), the
innerHTML will be equivalent to yourParameter.toString()
o Additional parameters
• None
 Since this binding sets your element’s content using innerHTML, you should be careful
not to use it with untrusted model values, because that might open the possibility of a
script injection attack. If you cannot guarantee that the content is safe to display, then
you can use the text binding, which will set the element’s text value using innerText or
textContent instead

11/16/2019 HCL Technologies 41


The "css" binding
 The css binding adds or removes one or more named CSS classes to the associated
DOM element. This is useful, for example, to highlight some value in red if it
becomes negative.
<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>

<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the
"profitWarning" class
};
viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>

11/16/2019 HCL Technologies 42


 Parameters
o Main parameter
• If you are using static CSS class names, then you can pass a JavaScript object in which the
property names are your CSS classes, and their values evaluate to true or false according to
whether the class should currently be applied.
• You can set multiple CSS classes at once.
o Additional parameters
• None
 CSS classes names must be legal JavaScript variable names

11/16/2019 HCL Technologies 43


The "style" binding
 The style binding adds or removes one or more style values to the associated DOM
element. This is useful, for example, to highlight some value in red if it becomes
negative, or to set the width of a bar to match a numerical value that changes.
<div data-bind="style: { color: currentProfit() < 0 ? 'red' : 'black' }">
Profit Information
</div>

<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially black
};
viewModel.currentProfit(-50); // Causes the DIV's contents to go red
</script>

11/16/2019 HCL Technologies 44


The "attr" binding
 The attr binding provides a generic way to set the value of any attribute for the
associated DOM element. This is useful, for example, when you need to set the title
attribute of an element, the src of an img tag, or the href of a link based on values in
your view model, with the attribute value being updated automatically whenever
the corresponding model property changes.
<a data-bind="attr: { href: url, title: details }">
Report
</a>

<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>

11/16/2019 HCL Technologies 45


End of Day 1 Session
THANKS FOR LISTENING…

11/16/2019 HCL Technologies 46

You might also like