1. Code Focused Training
Syed Awase Khirni
Syed Awase earned his PhD from University of Zurich in GIS, supported by EU V Framework Scholarship from SPIRIT Project (www.geo-spirit.org). He
currently provides consulting services through his startup www.territorialprescience.com and www.sycliq.com
{>}GROUND UP
JavaScript MVVM Framework
31. ONE-WAY DATA BINDING
• On request, the runtime retrieves
the source value and initializes
the specified target property to
that value.
• Each time the source value
changes the data binding retrieve
the new value and reinitialize the
target property
32. TWO-WAY DATA BINDING
• On request, the runtime retrieves
the source value and initializes
the specified target property to
that value.
• Each time the source value
changes, the data binding
retrieves the new values and
reinitializes the target property.
• Additionally, when the target
property changes value- e.g.
when the user types into an edit
control – the data binding
retrieves the new target property
value and propagates it back to
the source.
• Default type of data binding.
33. TRANSFORMERS
• Allows you to convert a value
from one form to another as it
propogates to and from a data
source to a target.
• A transformer is used to convert
a value from its internal
representation to a unique
displayed value.
• A transformer can also be used as
a data type converter.
• A transformer also receives the
culture information for the User
Interface as one of its
parameters, which can be used to
tailor the presented user
interface to suit the current
culture of the user.
46. Code Focused Training
3 Types of KO Observables
• Used for view model propertiesObservable
• Used for collections
Observable
arrays
• Encapsulate one or more other
observables
Dependent
observables
48. Code Focused Training
Reading and Writing Observable
Read
• Call the observables current
value, with no parameters.
Write
• To write a new value to the
observable, call the
observable and pass the new
value as a parameter.
Write Multiple Properties
• To write value to multiple observable
properties on a model object using
chaining.
53. Code Focused Training
KO Observable Arrays
• Used with Collections, They detect
changes to the collection of things.
• Useful in many scenarios when
displaying or editing multiple values
and need repeated sections of UI to
appear and disappear as items are
added and removed.
An observableArray tracks which
objects are in the array, not the
state of those objects
•Use Knockout array methods
•Cross browser
•Dependency Tracking
•Clean Syntax
56. Code Focused Training
Observable array methods
• Returns zero-based index of itemList.indexOf(“value”)
• Returns items between start/end indexList.slice(2,4)
• Adds new item to endList.push(“value”)
• Removes last itemList.pop()
• Inserts item at beginningList.unshift(“value”)
• Reverses orderList.reverse()
• Sorts the itemsList.sort()
• Removes specified itemList.remove(item)
• Removes all itemsList.removeAll()
69. Determining the observable type
Function Description
Ko.isObservable Returns true for observables, observable
arrays, and all computed observables
Ko.isWritableObservable Returns true for observables, observable
arrays, and writable computed
observables
Ko.isComputed Returns true for all computed observables
Ko.isPureComputed Returns true for pure computed
observables
70. Using the computed context
Function description
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.
getDependenciesC
ount()
returns the number of dependencies of the
computed observable detected so far during the
current evaluation
73. Why use Data Binding?
• KO’s data binding system gives us
an extremely powerful and
efficient way to bind data
between the model and the view.
• “data-bind” attribute is the glue
that it holds it all together.
– Comma separated options
– Completely valid with HTML5 as it
is a “data” attribute
– Many types of declarative bindings
• Jquery that does great things like
manipulating the DOM, BUT they
really lack the ability for the
model to send the data to UI.
74. Binding Values
• Can be a value, variable, literal or any type of
JavaScript expression
77. The visible binding
• Causes the associated DOM
element to become hidden or
visible according to the value you
pass to the binding.
78. The visible binding
• Using functions and expressions
to control element visibility
– We can use javascript function or
arbitrary javascript expression as
the parameter value.
79. The text binding
• Causes the associated DOM
element to display the text value
of your parameter
• Useful with elements like <span>
or <em> that traditionally display
text, but technically you can use
it with any element.
Usually used in <span> tags
80. The text binding
• Without a container element
– Sometimes you may want to set
text using KO without including an
extra element for the text binding.
81. The html binding
• Causes the associated DOM element
to display the HTML specified by your
parameter
• Useful when values in your view model
are actually strings of HTML markups
that you want to render.
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 script injection attack.
82. The css binding
• Adds or removes one or more
named css classes to the
associated DOM element.
• The below example will apply the
css class profitWarning whenever
the currentProfit value dips
below zero and remove that class
when ever it goes above zero
83. The css binding (with dynamic classes)
• Apply the css class profitPositive
when the currentProfit value is
positive, otherwise it will apply
the profitWarning CSS class.
84. The style binding
• Adds or removes one or more style
values to the associated DOM element.
• Useful 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.
• In the example below, the element’s
style.color property to red whenever
the currentProfit value dips below zero
and to black whenever it goes above
zero
http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html
85. The attr binding
• Provides a generic way to set the value
of any attribute for the associated
DOM element.
• Useful when we 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.
88. Click Binding
• Click binding adds an event
handler so the chosen javascript
will be invoked when the
associated element is clicked.
• Usually used with buttons, input
and links
89. Event Binding
• Event binding allows you to add
an event handler for a specific
event
• Used for events like keypress,
mouseover and mouseout
• You can also access the DOM
event object associated with your
event.
90. Submit Binding
• Adds an event handler so that a
specific function will be invoked
when the DOM element is
submitted
• Obviously this usually done using
a form element
91. Enable and Disable Binding
• The enable binding causes the
associated DOM element to only
be enabled when the value is
true
• Disable does the opposite and is
disabled when true
92. Value Binding
• The value binding is associated
with a property in the view
model.
• This is usually used on input,
select and textarea fields : 2 way
data binding.
93. Other Bindings
• hasFocus – links a DOM
element’s focus state with a
viewmodel property
• Checked – links checkable form
control to a view model property
• Options- shows which options
should appear in a drop-down
94.
95. Binding Contexts
• Object that holds data that can
be easily referenced from your
bindings.
• KO creates and manages a
context hierarchy
• The viewModel parameter is the
root level
• Each control flow binding creates
a new child binding context that
refers to the nested model data.
96. Parent Binding Contexts
• Current data bound item$data
• Item from parent binding context$parent
• Array containing all parent bindings contexts$parents
• Item at the top of the binding$root
97. $parent
• Context immediately outside the current context
• In the “root” context, this is undefined- the root has no parent
• $parent – array of all parent view models
• $parents[0] – aren’t context (same as $parent)
• $parents[1]- Grandparent context
• $parents[2]-Great-grandparent
98. $root
• Main view model object in the root context
• Topmost parent context
• Usually the object passed to ko.applyBindings
• Equivalent to $parents[$parents.length-1]
99. $component
• If you are in a component context, it refers to that components
view model
• Component-specific equivalent to $root
• If nested then refers to the closest component
100. $data
• View model object in the current context
• In $root context, $data and $root are the same
• Useful to reference the view model itself.
101. $index
• Only available within foreach bindings
• Zero-based index of the current array entry
• Observable and updated
102. $parentContext
• The binding context object at the parent level
• Different from $parent
• Can be used to access an index value of an outer foreach item
103. Others
• $rawData – Raw view model
value in the current context.
Usually the same as $data.
• $componentTemplateNodes-
Within the context of a particular
component template. An array
that holds any DOM nodes that
are passed to the component.
• $context – Current binding
context object
• $element – the element DOM
object of the current binding
106. The if binding
• The if binding causes a section of
markup to appear in your document (
and to have its data-bind attributes
applied), only if a specified expression
evaluates to true
• Physically adds or removes the
contained markup in the DOM and
only applies bindings to descendants
if the expression is true.
• If plays a similar role to the visible
binding.
• With visible, the contained markup
always remains in the DOM and always
has its data-bind attributes applied –
the visible binding just uses CSS to
toggle the container element’s
visibility.
111. With Binding
• Creates a new binding context
• Descendant elements are bound
in the context of a specified
object
• You can also use with other
control flow bindings such as if
and ifnot.
113. KO Utilities and Data Features
KO Utilities
• Ko.utils.arrayFilter
• Ko.utils.arrayFirst
• Ko.utils.arrayForEach
• Ko.utils.arrayIndexOf
• Ko.utils.arrayMap
• Ko.utils.arrayPushAll
• Ko.utils.arrayRemoveItem
• Ko.utils.compareArrays
• Ko.utils.unwrapObservable
Data Features
• Ko.toJS()
– JavaScriptObject with just data and no
knockout constructs
• Ko.toJSON()
– Produces JSON string representing view
model’s data (calls ko.toJS() internally)
114.
115. Templating?
• Templating gives us a
simple and elegant way
to build professional
looking user interface
structures
• Templating Type
–Native templating
–String Based Templating
116. Native Templating
• Supports control flow
bindings ( foreach, if,
with)
• Captures HTML
markup and uses it as a
template to render
against arbitrary data
items
• Built into knockout and
no external libraries
are needed.
117. String-Based Templating
• Connects Knockout to a 3rd
party engine
• Knockout can pass model
values to the external
template engine
• Knockout injects the resulting
markup string into the
document.
118. Binding parameters
Name ID of the element with the template you wish to render
Nodes Array of DOM nodes to use as a template (non-observable
array)
Data Object to supply the data to be rendered
If If provided, the template will only render if true
Foreach Renders a template in foreach mode
As Defines alias for items being rendered
afterRender, afterAdd,
beforeRemove
Callbacks to invoke against rendered DOM elements
119. Dynamic Choosing
• If you have multiple names templates, you can pass an
observable for the name option.
• As the value is updated, the element contents will be re-
rendered using the correct template
• You could also pass a callback function to choose the correct
template.
123. Custom Bindings
• When we want more control and
flexibility over elements and
observables used.
• To create our own interactive
controls, we use custom binding.
• All the bindings available in
knockoutJS are the sub
properties of a
“ko.bindingHandlers” object.
• Create a custom binding
– Add a property with your
custom binding name
– Assign an object with two call
back functions.
124. Custom bindings
init
– Init callback: executed when the binding is
applied the very first time. The initial setup
necessary for the custom binding such as
attaching events, setting up the initial state
for variable and so on.
– The init callback function will be called
only when the binding is applied
update
• Update callback: called whenever the
associated observable is changed.
• While binding your custom binding handler
with the element, if you have associated /
assigned an observable to your custom binding
handler then update call back will be executed
whenever you change the associated/assigned
observable.
125. Custom bindings (Parameters of callback functions)
Tag Description
Element DOM element on which our custom binding is applied
ValueAccessor The javascript function that will return the value/assigned/associated with the binding. Use
“ko.unwrap”utility function to get the value assigned
allBindingAccessor The JavaScript function that will return all the values assigned/associated with
all the bindings bound with the current DOM. Suppose you have some other KO bindings say value,
visible then the allBindingAccessor will give you those values and visible binding values also.
viewModel he viewmodel object that is bound to the entire page using "ko.applyBindings()". But when your
binding is within the with binding or foreach binding then the viewModel parameter will have
the $data context instead of the main viewModel.
bindingContext The binding context available for the DOM element. This parameter will have all other bindings
($parent, $parents and $root...)
as a special property.
These init and update callback functions have the same set of parameters. They are
element, valueAccessor, allBindingsAccessor, viewModel and bindingContext
126.
127. Components
• Components are a clean and
powerful way of organizing your
UI code into modular , reusable
chunks
• Most beneficial for large
applications
• Simplifies development
• Improves runtime performance
of your application.
128. Components
Advantages
• Represent individual controls and
widgets or an entire section
• Contain their own view and view
model
• Be loaded asynchronously
• Receive parameters
• Nested and inherited
• Packaged easily.
Registering a component.
• ViewModel is optional
• Template is required.
129. Specifying a template
• Existing Element ID
• Existing Element instance
• String of MARKUP
• Array of DOM Nodes
• Document Fragment
• AMD Module
134. ViewModel Key
• Can be a function
• Can be passed instance to use
object directly
• Can pass createViewModel to call
a function that acts as a factory.
136. Creating Components
• Custom Elements: Provide a
convenient way of injecting
components into views
– Convenient syntax for creating
components
– <like-button>, <date-slider>, <login-
form>
– Knockout takes care of
compatibility (IE6 to IE8 need to
register before parsing HTML)
– Great way to organize code
• Component binding- injects a
specific component into an
element with optional
parameters.
• Works extremely similar to
custom element and in many
cases does the exact same thing
139. Component Binding Full API
• Name- the name of the
component
• Params – Object passed to
component. Usually a key-value
object containing multiple
parameters, and usually received
by the component’s viewmodel
constructor
140. Component Life Cycle
• Component loaders supply vm and template1
• Template is cloned and injected2
• Vm is instantiated3
• Vm is bound to view4
• Component is active5
• Component is torn down and view model is disposed6
141. 1. Component Loaders supply vm and template
• Multiple component loaders may be consulted
• Process takes place once per component type
• Supplies vm/templates based on what is registered.
• Asynchronous process
142. 2.Template is Cloned
• Template is cloned and injected into the container element
• Any existing content is removed and discarded
143. 3. ViewModel is instantiated
• If there is a view model- they are not required though
• If given a constructor, knockout called new
viewModelName(params)
• createViewModel is called if given
• Always synchronous
144. 4. ViewModel is bound to view
• If no viewmodel, then view is bound to any params supplied to
the component binding
145. 5. Component is active
• Component is operating and can be on-screen as long as
needed.
• If any params are observable, the component can observe
changes or write back modified values
• Communicates cleanly with parent
146. 6.Component is torn down
• Component is torn down and the viewmodel is disposed
• Name values changes observably
• Dispose function on the viewmodel is called
• If user navigates to new page browsers do automatically
• Memory from objects is released.
151. EMIT JSON DATA
• View models are JavaScript Objects,
which can be published as a JSON
object using JSON serializers like
JSON.stringify or json2.js
• BUT YOUR VIEW MODELS PROBABLY
CONTAIN OBSERVABLES, COMPUTED
OBSERVABLES AND OBSERVABLE
ARRAYS, which are implemented as
Javascript functions and therefore
won’t always serialize cleanly.
• Ko.toJS -> clones your viewmodel’s
object graph, substituting for each
observable the current value of that
observable, so you get a plain copy
that contains only your data and no
knockout related artifact.
• Ko.toJSON – produces a JSON string
representing your view model’s data.
Internally, it simply calls to ko.toJS on
your view model and then uses the
browser’s native JSON serializer on the
result.