SlideShare a Scribd company logo
1 of 153
Download to read offline
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
Code Focused Training
Why NOT JQUERY?
• Jquery isn’t usually used for
complex web apps
•No easy way for the UI and
the data to communicate
•More complex way to interact
with the data model
•Client Side validations and
AJAX calls
•DOM Manipulation Library
•Limited to Form and UI
Interactions
© Syed Awase 2015-16 - KnockOut Ground Up! 2
What is KnockOut?
• Knockout.js is a JavaScript library
that enables you to declaratively
bind elements against model data
with two-way updates happening
automatically between your UI
and model.
• KO is a data-binding library while
AngularJS is a full-framework.
• Angular uses routes, directives
and services , while KO does not.
• JavaScript MVVM Framework
• MVVM – Model-View-ViewModel
• Model – Objects in your business
domain
• View – User Interface that is visible to
the user
• ViewModel – code representing
data/operations on a UI (Presentation
Concerns)
• Complimentary to other JavaScript
Frameworks
• E.g. Jquery, CoffeScript, Prototype, etc.
© Syed Awase 2015-16 - KnockOut Ground Up! 3
Code Focused Training
Knockout
© Syed Awase 2015-16 - KnockOut Ground Up! 4
knockout-3.4.0.js
http://knockoutjs.com/downloads/knockout-3.4.0.js
Referencing in your application
Works on any mainstream browser (IE 6+,
Firefox 2+, Chrome, Safari, Edge, others)
http://www.knockmeout.net/
Code Focused Training
© Syed Awase 2015-16 - KnockOut Ground Up! 5
Knockout
“A java script library that helps you to
create rich, responsive display and editor
UI with a clean underlying data model.
Anytime you have section of UI that
update dynamically, KO can help you
implement it more simply and easily
maintainable”
Client side data binding library for building
data-aware web applications
Why Knockout?
• Developing a complex and dynamic data-driven web
application can be a challenging task.
• Keeping a user interface in sync with the underlying data
normally involves wiring up a number of event handlers to
broker information between the various elements and the data
whenever any actions are performed by a user or when new
data is loaded.
© Syed Awase 2015-16 - KnockOut Ground Up! 6
Code Focused Training
© Syed Awase 2015-16 - KnockOut Ground Up! 7
DECLARATIVE BINDING
Easily associate DOM
elements with model
data using a concise
readable syntax
AUTOMATIC UI REFRESH
When your data
model’s state
changes, your UI
updates automatically
TEMPLATING
Quickly generate
sophisticated, nested
Uis as a function of
your model data
UI
DEPENDENCY
TRACKING
Implicitly set up
chains of
relationships
between model data,
to transform and
combine it
Code Focused Training
Traditional UI Development
MODEL VIEW
© Syed Awase 2015-16 - KnockOut Ground Up! 8
DOMAIN
OBJECTS
UI
Layout
Code
behind
Update
Fetch data
Code Focused Training
Traditional UI Development
Constraints
• Difficult to test
• Encourages using UI as a data storage
• Complex classes and huge amount of code
• No Code sharing
• Very strong dependency between UI and Logic
• Redeisgn requires a lot of effort
Why MVVM
© Syed Awase 2015-16 - KnockOut Ground Up! 9
Clear responsibilities between the developers and designers
Code Focused Training
Knockout Architecture
© Syed Awase 2015-16 - KnockOut Ground Up! 10
MODEL
BUSINESS LOGIC AND DATA
VIEW MODEL
USER INTERFACE
VIEW MODEL
PRESENTATION LOGIC
JAVASCRIPT
REMOTING
INSTANT NOTIFICATIONS
TWO WAY DATABINDING
COMMANDS EXECUTION
Code Focused Training
Design Patterns and Architectural Guide
© Syed Awase 2015-16 - KnockOut Ground Up! 11
Design Patterns are essentially time tested solutions to recurring design problems.
SOME DESIGN PATTERNS USED FOR KNOCKOUT
MVVM
OBSERVER
JAVASCRIPTCLOSURE
MODULEPATTERN
Code Focused Training
Presentation Design Pattern
© Syed Awase 2015-16 - KnockOut Ground Up! 12
MVVM MVP MVC
Model-View-ViewModel Model-View-Presentation Model-View-Controller
UI Centric Design Patterns
SEPARATION OF CONCERNS CODE REUSABLITY UNIT TESTING SPA DECOUPLING
Code Focused Training
MVC
© Syed Awase 2015-16 - KnockOut Ground Up! 13
VIEW
CONTROLLER MODEL
Passes
Calls to
Manipulates
Fires
Events
User Input
• Controller contains the logic that alters the
model depending on the action triggered by
UI.
• View is a composite implementation, A
view can switch controllers or a single
controller can be used by multiple views.
View subscribes to changes done to the
model
• controller manipulates the data but
asserting the changes from a view
perspective
Code Focused Training
MVP
© Syed Awase 2015-16 - KnockOut Ground Up! 14
VIEW
PRESENTER
MODEL
Passes
Calls to
Manipulates
Fires
Events
User Input
• Controller is replaced by Presenter , it presents the changes
done in model back to view.
• Presenter here takes the responsibility of not only
manipulating model but also updating the view.
•MVP Variations
•Supervising controller : uses a controller both to handle
input response but also to manipulate the view to handle
more complex view logic. It leaves simple view behavior to
the declarative system, intervening only when effects are
needed that are beyond what can be achieved
declaratively
• Passive View handles this by reducing the behaviour of
UI components to the absolute minimum by using a
controller that not just handles responses to user events,
but also does all the updating of the view. Allows testing to
be focused on the controller with little risk of the problem
in the view.
Updates
Code Focused Training
Real World MVC
• Controllers are “almost” not reusable
• Controllers are large
• View is very tight to it’s controller
• Controllers are hard to unit test
•
© Syed Awase 2015-16 - KnockOut Ground Up! 15
MVC
VIEW
CONTROLLER
VIEW MODEL
Code Focused Training
MVVM
© Syed Awase 2015-16 - KnockOut Ground Up! 16
VIEW
CONTROLLER
VIEW MODEL
MODEL
VIEWS UNIT TESTS
VIEWMODELS
MODEL DB
ENTITIES
Binding, Commands, Data Templates
User Controls
The Model
• The applications stored data
• Independent of the UI
• Ajax calls to read/write to and from the stored data
© Syed Awase 2015-16 - KnockOut Ground Up! 17
The View Model
• Code representation of the data and operations
• Not the UI itself
• Pure javascript
• Holds unsaved data
The View
• Visible UI
• Displays ViewModel Information
• Updates when the State changes
• HTML Document with Declarative Bindings + CSS3 Styling.
Code Focused Training
MVVM • View Model does not need a reference to a VIEW
• ViewModel coordinates with one or more models,
exposes properties for the view to bind to.
• views know about the ViewModel but not the
model
• ViewModel knows about the Model but not the
View
• Model Knows about itself
• View binds to properties in the ViewModel
• .Changes to properties in the ViewModel
automatically propogate to the View – no additional
code required
• Data Changes made in the ViewModel, never the
View
• More testable than MVC or MVP
© Syed Awase 2015-16 - KnockOut Ground Up! 20
VIEW
VIEWMODEL
MODEL
Passes
Calls to
Manipulates
Fires
Events
User Input
Code Focused Training
MVVM BENEFITS
• Modularity
• Decoupling components
• Allows each component to be versioned
independently
• Flexibility
• Multiple views for one Model (web front end,
desktop front end, mobile front end, etc)
• Replace one component (replace data storage
from flat file to database)
• Maintainability
• Only change one component where bug exists,
less risk in late changes
• Testability
• Each component communicates through
contract so each component can be unit-tested
independently
VIEW MODEL ACTS AS A COMPLETE MIRROR OF
THE VIEW
© Syed Awase 2015-16 - KnockOut Ground Up! 21
VIEW
VIEWMODEL
MODEL BUSINESS LOGIC
PRESENTATION
LOGIC
UI LOGIC
NOTIFICATION
DATABINDING
Code Focused Training
View
• UserControl based
• XAML
• Minimal code behind
• Data Context set to the
associated VIEWMODEL
• No Event Handlers
• Databinding pushes the
changes from the
ViewModel to View and
from View to ViewModel
• Loosely coupled, can
easily replace the view
without affecting the view
model © Syed Awase 2015-16 - KnockOut Ground Up! 22
ViewModel
• Implements
INotifyPropertyChanged
• Expose Icommand
• Handle Validation
• Adapter class between
the View and the Model
• Listen to the Model’s
events
• Testable
Model
• Event Based
mechanism to signal
changes to the
ViewModel
VIEWMODEL
VIEW MODEL
Code Focused Training
MODEL
• Non-visual classes that
encapsulate the application’s data
and business logic
• Can’t see ViewModel or View
• Should not contain any use case-
specific or user-task-specific
behaviour or application logic
• Notifies Other components of any
state changes
• May provide data validation and
error reporitng.
VIEW MODEL
•Non-visual class encapsulates
the presentation logic required
•Can’t see View ( no direct
references)
•Coordinates the View’s
interactions with the model
•May provide data validation
and error reporting
•Notifies the view of any state
changes
© Syed Awase 2015-16 - KnockOut Ground Up! 23
Code Focused Training
VIEW
•Visual element defines the
controls and their visual layout
and styling
•Can see all other components
•Defines and handles UI visual
behaviour, such as animations
or transitions
•Code behind may contain
code that requires direct
references to specific UI
controls
View  ViewModel
Interaction
Ways
Data
Binding
Commands Notifications
© Syed Awase 2015-16 - KnockOut Ground Up! 24
Code Focused Training
MVP vs.MVC vs.MVVM
MVP(Presenter) MVC(Controller) MVVM(ViewModel)
View Communicates with the
presenter by directly calling
functions on an instance of the
presenter
View sends input events to the
controller via a callback or
registered handler
View binds directly to the View
Model
The presenter communicates with
the view by taking to an interface
implemented by the view
View receives updates directly from
the model without having to go
through the controller
Changes in view are automatically
reflected in ViewModel and
viceversa
Use where binding via a data
context is not possible
Use where the connection between
the view and the rest of the program
is not always available
Use where binding via a data
context is possible.
© Syed Awase 2015-16 - KnockOut Ground Up! 25
e.g. Windows Forms e.g. SmallTalk, ASP.NET MVC e.g. WPF, KO,AngularJS
Code Focused Training
MVVM
© Syed Awase 2015-16 - KnockOut Ground Up! 26
• Enable UI Unit Testing
• WPF Line of Business Application
• Layers represent Separation of
concerns and decoupling
• Enables designer – developer workflow
• Is a natural pattern given WPF’s rich
data binding that promotes loose
coupling
• Takes full advantage of WPF’s
DataTemplates and Commands
• UI (view) can be swapped out without
touching the UI code
Code Focused Training
MVVM
Advantages
• Separation of concerns
• Can use unit tests
• Designers and developers can
work synchronously
• Easy to redisgn the UI
• Can share code easily
Disadvantages
•Harder to debug
•May affect performance
•More files to serve the
architecture
© Syed Awase 2015-16 - KnockOut Ground Up! 27
Code Focused Training
DataBinding (State)
• Process that establishes a connection between
the application UI and application logic
• When the data changes its value, the elements
that are bound to the data reflect changes
automatically
• Direction of data flow
• One Time: binding update the target with
the source data when binding is created
• One Way bindings update the target with
the source data when the binding is
created, and any time the data changes.
This is the default mode.
• Two Way bindings update both the target
and the source when either changes
© Syed Awase 2015-16 - KnockOut Ground Up! 28
Dependency
Property
Property
VIEW VIEWMODEL
Dependency Object Object
BINDING TARGET BINDING SOURCE
Provides an easy and efficient
method to connect information
to a user interface that displays
the data
Code Focused Training
Data Binding
Options
• Directions of the data flow
•One way
• Two way
• One time
• One way to Source
•What triggers source updates
(LostFocus, PropertyChanged, Explicit,
…)
•Bind to Objects, Collections, UI
Elements
• Path, Value Converters, Async,
Fallback, StringFormat
One Time: the data is set when binding is
intialized-mostly used in ReadOnly mode
OneWay: Updates the data from source to
target, so if source changes the target is notified.
Two way: Updates data from source to taget and
vice-versa, so if the source changes the target is
notified or vice versa
© Syed Awase 2015-16 - KnockOut Ground Up! 29
ONE-TIME DATA BINDING
• When you request one-time data
binding, the run-time, using the
data source and the specified
path, retrieves the source value
and initializes the specified target
property to that value.
• No change occurs subsequently
when the source or the target
property value is changed.
• Two Special Cases
– When the DataContext of an
element changes, effectively, the
data source has changed and
therefore the binding performs
another one-time transfer
– In many cases, the DataContext
refers to a collection of objects.
When the current object for a
collection changes, the databinding
performs a one-time transfer.
© Syed Awase 2015-16 - KnockOut Ground Up! 30
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
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.
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.
Code Focused Training
Commands (Behaviour)
•Provide a way to represent
actions or operations that
can be easily bound to
controls in the UI
•Encapsulate the actual
code that implements the
action or operation
•Examples: Button Click,
List selection changed
• OnPropertyChanged method
is required to notify binding
target properties with change in
source
• Observable Collection needed
for binding lists source
•Implementing
InotifyPropertyChanged and
INotifyCollectionChanged
interface
© Syed Awase 2015-16 - KnockOut Ground Up! 34
Code Focused Training
Data Templates
• Converts non-visual data into
its visual representation
•Defines how a view model will
be rendered or can modify its
default visual representation
without changing the
underlying object itself or the
behavior of the control that is
used to display it.
Simple datatemplate using
HTML Listbox Control
© Syed Awase 2015-16 - KnockOut Ground Up! 35
Code Focused Training
Observer Pattern
• A behavioral pattern used to assure
consistency between objects
• Used to establish relationship between objects
at runtime not compile time
• Define a one-to-many dependency between
objects so that when one object changes
state, all its dependents are notified and
updated automatically
• Object that changes is called “Subject”
• Object that receives updates is called
“Object”
• Two Approaches
• Pull model: Observer invokes method
requesting data
• Push model: subject passes data to
observer as argument at update()
Similar to NewsPaper Subscription
Publisher publishes and subscribers
read
Once subscribers unsubscribe,
subscribers won’
Once subscribers subscribe again
they get to read
Publishers are Subject and
Subscribers are Observer
© Syed Awase 2015-16 - KnockOut Ground Up! 36
Code Focused Training
Observer Pattern
Benefits
• Objects are loosely coupled with each other but
still communicate properly
• Observers can be added/removed at any time
• Subject and Observer can belong to different
abstraction layers
• Subject does not need to know the concrete
class of an observer, just that each observer
implements the update interface
• Observers can be added without modifying the
subject
Usage
• Used when there is one to many
relationship between object such as if one
object is modified, its dependent objects
are to be notified automatically
• When an abstraction has two aspects, one
dependent on the other. Encapsulating
these aspects in separate objects lets you
vary and reuse them independently.
© Syed Awase 2015-16 - KnockOut Ground Up! 37
Code Focused Training
IIFE
• A javascript design pattern which
produces a lexical scope, using
Javascript’s function scoping.
• IIFE is used to avoid variable
hoisting from withinblocks, protect
against polluting the global
environment and simultaneously
allow public access to methods
while retaining privacy for variables
defined with the function
• Emulate privacy
© Syed Awase 2015-16 - KnockOut Ground Up! 38
Code Focused Training
Module Pattern
• Help in keeping the units
of code for a project both
cleanly separated and
organized.
• originally defined as a
way to provide both private
and public encapsulation
for classes in conventional
software engineering.
• The module pattern
encapsulates “privacy”, state
and organization using
closures. It provides a way of
wrapping a mix of public and
private methods and
variables, protecting pieces
from leaking into the global
scope and accidentally
colliding with another
developer’s interface
© Syed Awase 2015-16 - KnockOut Ground Up! 39
Code Focused Training
Revealing Module Pattern
• Advantages :
• More consistent syntax.
• Clear outline of functions and variables
which can be accessed publicly which
eases readability.
• Disadvantages:
• If a private function refers to a public
function, that public function cannot be
overridden if a patch is necessary. The
private function will continue to refer to the
private implementation and the pattern
does not apply to public members, only to
functions
• Public object members which refer to
private variables are also subject to the
no-patch rule
© Syed Awase 2015-16 - KnockOut Ground Up! 40
Code Focused Training
Singleton Pattern
• It restricts instantiation of a class to a single
object.
• It can be implemented by creating a class with
a method that creates a new instance of the
class if one doesnot exist.
• In the event of an instance already existing. It
simply returns a reference to that object.
• They serve as a shared resource namespace
which isolate implementation code from global
namespace so as to provide a single point of
access for functions.
© Syed Awase 2015-16 - KnockOut Ground Up! 41
Code Focused Training
Observer Pattern
• A design pattern where an object (known
as a subject) maintains a list of objects
depending on it (observers), automatically
notifying them of any changes to state.
• When a subject needs to notify observers
about something interesting happening. It
broadcasts a notification to the observers
( which can include specific data related to
the topic of the notification).
• When we no longer wish for a particular
observer to be notified of changes by the
subject they are registered with, the
subject can remove them from the list of
observers.
• Encourages us to think hard about the
relationships between different parts of our
application.
• Help in identifying the layers containing direct
relationships which could instead be replaced
with sets of subjects and observers.
• Modular application development, more
loosely coupled block to improve code
management and reusability.
• Dynamic relationships can exist between
observers and subjects.
• Sometimes, difficult to obtain guarantees that
particular parts of our applications are
functioning as we may expect.
© Syed Awase 2015-16 - KnockOut Ground Up! 42
Code Focused Training
KO DEBUGGING TOOLS
© Syed Awase 2015-16 - KnockOut Ground Up! 43
KO CONTEXT DEBUGGER
https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof?hl=en
GLIMSE FROM NUGET PACKAGE MANAGER
Code Focused Training
KO Core
© Syed Awase 2015-16 - KnockOut Ground Up! 44
Code Focused Training
Activating Knockout
• Include knockout.js core files using
script include tags
• Apply Binding using ko.applyBindings
• The first parameter says what viewModel
object to use with declarative bindings,
which is activated.
• Optionally, it takes a second parameter to
define which part of the document to
search for data-bind attributes. Useful in
the case of multiple viewModels and
associate each viewModel with a different
region of a page.
© Syed Awase 2015-16 - KnockOut Ground Up! 45
Step 2: Include ko.applyBindings(ViewModel)
should be same
Step 1: Include knockout.js resource
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
KO Observables
• JavaScript functions
– Not all browsers support javascript getter
and setter functions
• Internally Knockout JS’s binding
observe the Observables
• Used to detect and respond to changes
on an object
• Allows for 2 way data binding, by
notifying subscribers about the
changes and can automatically detect
dependencies.
• Can be subscribed to
© Syed Awase 2015-16 - KnockOut Ground Up! 47
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.
Code Focused Training
Explicitly subscribing to observables
• To register your own subscriptions
to be notified of changes to
observables, use subscribe
function
• Subscribe function takes in
3(three) parameters
• Callback – the function that is
called whenever the notification
happens
• Target – defines the value of
this in the call back function
• Event- name of the event to
receive notification for
© Syed Awase 2015-16 - KnockOut Ground Up! 49
Advanced Concept
Code Focused Training
Explicitly subscribing to observables
• Dispose: this function is used to
terminate a subscription if you wish
to. First capture the return value as
a variable
© Syed Awase 2015-16 - KnockOut Ground Up! 50
Advanced Concept
• beforeChange Event: if you want
to be notified of the value of an
observable before it is about to be
changed.
Code Focused Training
Explicitly subscribing to observables
• Dispose: this function is used to
terminate a subscription if you wish
to. First capture the return value as
a variable
© Syed Awase 2015-16 - KnockOut Ground Up! 51
Advanced Concept
• beforeChange Event: if you want
to be notified of the value of an
observable before it is about to be
changed.
Code Focused Training
Observables
Notify subscribers: notify
• Used to notify observable’s subscriber
on write, even if the value is the same.
• When writing to an observable that
contains a primitive value( number,
string, boolean or null) the
dependencies of the observersable are
normally ONLY notified if the value
actually changed.
Delay/Suppress Change
Notification :rateLimit
• An observable notifies its subscribers
immediately, as soon as it’s changed. But if the
observable is changed repeatedly or triggers
expensive updates, we may get better
performance by limiting or delaying the
observable’s change notifications.
© Syed Awase 2015-16 - KnockOut Ground Up! 52
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
Code Focused Training
Prepopulating an ObservableArray
• Developers can populate
the observable array by
passing in some initial
items as an array to the
constructor
© Syed Awase 2015-16 - KnockOut Ground Up! 54
Code Focused Training
Reading an observableArray
• An observableArray is an
observable whose value is an
array.
• The underlying array can be
invoked as a function with no
parameters.
• native javascript array functions
can be used to operate on the
underlying array.
• indexOf: returns an index of the
first array item that equals your
parameter.
• Modify the contents of an array.
KO’s methods automatically trigger
the dependency tracking
mechanisms so that all registered
listeners are notified.
• Push,Splice ,pop,shift,
unshift,reverse, sort, splice
© Syed Awase 2015-16 - KnockOut Ground Up! 55
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()
Code Focused Training
Manipulating an ObservableArray
Push(value)
• Adds a new
item to the end
of the array
© Syed Awase 2015-16 - KnockOut Ground Up! 57
Pop(value)
• Removes the
last value from
the array and
returns it
Unshift(value)
• Inserts a new
item at the
beginning of the
array
Code Focused Training
Manipulating an ObservableArray
Shift()
• Removes the
first value from
the array and
returns it
© Syed Awase 2015-16 - KnockOut Ground Up! 58
Reverse(value)
•Reverses the
order of the array
and returns the
observableArray(
not the
underlying array)
Sort()
• sorts the array
contents and
returns the
observableArray
Code Focused Training
Manipulating an ObservableArray
Splice()
• Removes and
returns a given
number of
elements
starting from a
given index.
© Syed Awase 2015-16 - KnockOut Ground Up! 59
Remove
• removes all the
values that equal
someItem and
returns them as
an array
RemoveAll
• removes all
values that
equal a value
and returns
them as an
array.
Code Focused Training
Manipulating an ObservableArray
Destroy()
• Finds any
objects in the
array that equal
someItem and
gives them a
special property
called _destroy
with value true
© Syed Awase 2015-16 - KnockOut Ground Up! 60
DestroyAll()
• Finds any
objects in the
array that are
equal to a given
object, and gives
them a special
property called
_destroy with a
value true
Delay/Suppress:rateL
imit
• Similar to delay
and suppressing
in observable,
they are used to
improve
performance by
limiting or
delaying change
notifications.
Code Focused Training
Dependent ObservablesEncapsulate one or more observables
Need to manage this pointer
Code Focused Training
Computed Observables
• Functions that are dependent on
one or more other observables and
will automatically update whenever
any of these dependencies
change.
• Evaluator function is called once
each time any of its dependencies
change and whatever value it
returns will be passed on to the
observers such as UI elements or
other computed observable
© Syed Awase 2015-16 - KnockOut Ground Up! 62
Code Focused Training
Pure Computed Observables
• If your computed observable
simply calculates and returns a
value based on some observable
dependencies, then it’s better to
declare it as a ko.pureComputed
• Its evaluator does not directly
modify other objects or state.
• KO can more efficiently manage its
re-evaluation and memory use.
• KO will automatically suspend or
release it if no other code has an
active dependency on it.
© Syed Awase 2015-16 - KnockOut Ground Up! 63
Code Focused Training
PureComputed Observable
Notify extender
• 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.
• Use 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.
Ratelimit extender
• As the dependencies change, a computed
observable updates and notifies its subscribers
immediately.
• To improve the performance by limiting or
delaying the computed observable’s updates
and notifications.
© Syed Awase 2015-16 - KnockOut Ground Up! 64
Code Focused Training
Determining if Computed Observable
• To check if it is a computed observable.
• ko.isComputed  returns true or false if it is
computed Observable or not
• Ko.isObservable  returns true for
observables, observable arrays and all
computed observables.
• Ko.isWritableObservable  returns true for
observables, observable arrays, writable
computed observables
• If you ONLY need to use the compound full
name in the UI
• KO will create a computed observable
internally in order to detect what observables
the expression depends on and will
automatically dispose it, when the associated
elements are removed.
© Syed Awase 2015-16 - KnockOut Ground Up! 65
UI Computed Observables
Code Focused Training
Constructing a computed observable
© Syed Awase 2015-16 - KnockOut Ground Up! 66
• 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 your
callback functions.
• options – An object with further
properties for the computed observable
A 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 your computed observable. It’s up to you to
supply custom logic to handle the incoming
values, typically by writing the values to some
underlying observable(s)
Code Focused Training
Constructing a Computed Observable
© Syed Awase 2015-16 - KnockOut Ground Up! 67
Constructs a pure computed
observable using the given
evaluator function and optional
object to use for this. Unlike
ko.computed, this method
doesn’t accept
an options parameter.
Constructs a pure computed
observable using
an optionsobject. This
accepts the read, write,
and owner options
Using a computed Observable
function Description
Dispose() Manually disposes the computed observable, clearing all
subscriptions to dependencies
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 subscripts
isActive() Returns whether the computed observable may be updated
in the future.
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.
© Syed Awase 2015-16 - KnockOut Ground Up! 68
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
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
Built-in Bindings: 4.Template
© Syed Awase 2015-16 - KnockOut Ground Up! 72
•Traditional JavaScript
template in <script> tag
JavaScript
Templates
•Template-less,
comment-based syntax
Containerless
Control flow
(Annonymous)
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.
Binding Values
• Can be a value, variable, literal or any type of
JavaScript expression
Code Focused Training
KO Bindings
 Built-in Bindings
Text and
Appearance
Forms
Control Flow
Templates
 Custom Binding
 indispensible tools for
any knockout developer
and is one of the best
extensibility points that
knockout has
© Syed Awase 2015-16 - KnockOut Ground Up! 75
Built-in Bindings: 1.Text and Appearance
© Syed Awase 2015-16 - KnockOut Ground Up! 76
• Toggle visibility of the DOM ElementVisible
• Text value of DOM elementText
• Raw HTML of DOM elementhtml
• CSS class(es) of DOM elementCss
• Raw style attribute of DOM elementStyle
• Any arbitrary attribute of DOM elementAttr
The visible binding
• Causes the associated DOM
element to become hidden or
visible according to the value you
pass to the binding.
The visible binding
• Using functions and expressions
to control element visibility
– We can use javascript function or
arbitrary javascript expression as
the parameter value.
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
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.
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.
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
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.
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
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.
Built-in Bindings: 2.FORMS
© Syed Awase 2015-16 - KnockOut Ground Up! 87
• Handler invoked when DOM element clickedClick
• Handler invoked for arbitrary event on DOM elementEvent
• Handler invoked when form submittedSubmit
• DOM element enabled if trueEnable
• DOM element disabled if trueDisable
• Any arbitrary attribute of DOM elementValue
• Attached to checkbox and radio buttonchecked
• Collection of elements in dropdown or multi-selectoptions
• Currently selected item(s) of dropdown or multi-selectselectedOptions
• Ensures DOM element has “name” attributeuniqueName
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
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.
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
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
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.
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
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.
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
$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
$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]
$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
$data
• View model object in the current context
• In $root context, $data and $root are the same
• Useful to reference the view model itself.
$index
• Only available within foreach bindings
• Zero-based index of the current array entry
• Observable and updated
$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
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
Built-in Bindings: CONTROL FLOW
© Syed Awase 2015-16 - KnockOut Ground Up! 105
• Executes if condition is trueif
• Executes if condition is falseifnot
• Executes for each item in collectionForeach
• Executes for object specified (child models)With
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.
The if binding
• “if” binding without a container
element
Iterating over an array
Add/remove records
KO Data Features
© Syed Awase 2015-16 - KnockOut Ground Up! 110
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.
Component Binding
• Injects a specific component into an
element
• Optional param
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)
Templating?
• Templating gives us a
simple and elegant way
to build professional
looking user interface
structures
• Templating Type
–Native templating
–String Based Templating
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.
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.
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
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.
Underscore Template Engine
Custom Bindings
• The most important extensibility functionality of knockoutjs
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.
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.
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
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.
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.
Specifying a template
• Existing Element ID
• Existing Element instance
• String of MARKUP
• Array of DOM Nodes
• Document Fragment
• AMD Module
Element Instance
String of MARKUP
Array of DOM Nodes
AMD MODULE (e.g.RequireJS)
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.
Synchronous/Asynchronous loading
• Can be set in registration
(synchronous :false)
• Default is asynchrnous
• Sometimes it has no choice.
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
Passing parameters
• Interpreted like a JavaScript
object literal
• You can pass arbitrary values of
any type
Component Binding
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
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
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
2.Template is Cloned
• Template is cloned and injected into the container element
• Any existing content is removed and discarded
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
4. ViewModel is bound to view
• If no viewmodel, then view is bound to any params supplied to
the component binding
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
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.
Template-Only Components
• The object to which the view is
bound is the params object
passed to the component binding
Containerless Components
• Passing Params
Passing markup
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.
EMIT JSON DATA
Code Focused Training
sak@sycliq.com
sak@territorialprescience.com
Contact Us
Thank You
We also provide Code Focused Open House Trainings
153© Syed Awase 2015-16 - KnockOut Ground Up!
For code driven trainings
Reach out to us +91-9035433124
Current Offerings
• AngularJS 1.5.x
• TypeScirpt
• AngularJS 2
• KnockOutJS
• BackBoneJS
• Ember JS
• Responsive Web Design with Bootstrap, Google
Material Design and KendoUI
• C# ASP.NET MVC
• C# ASP.NET WEB API
• C# ASP.NET WCF, WPF
• JAVA , SPRING, HIBERNATE
• Python , Django
• R Statistical Programming
INDIA
HYDERABAD | BANGALORE | CHENNAI | PUNE
OVERSEAS
SINGAPORE | MALAYSIA | DUBAI

More Related Content

What's hot

MVVM Design Pattern NDC2009
MVVM Design Pattern NDC2009MVVM Design Pattern NDC2009
MVVM Design Pattern NDC2009Jonas Follesø
 
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.jsAsynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.jsChristian Heindel
 
當ZK遇見Front-End
當ZK遇見Front-End當ZK遇見Front-End
當ZK遇見Front-End祁源 朱
 
Angular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page ApplicationAngular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page ApplicationEdureka!
 
Angular JS Basics
Angular JS BasicsAngular JS Basics
Angular JS BasicsMounish Sai
 
Live Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS FeatuesLive Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS FeatuesEdureka!
 
AngularJS - A Powerful Framework For Web Applications
AngularJS - A Powerful Framework For Web ApplicationsAngularJS - A Powerful Framework For Web Applications
AngularJS - A Powerful Framework For Web ApplicationsIdexcel Technologies
 
The dashboarding problem
The dashboarding problemThe dashboarding problem
The dashboarding problemnuria_ruiz
 
Portal Integration with SAP BusinessObjects (SDK)
Portal Integration with SAP BusinessObjects (SDK)Portal Integration with SAP BusinessObjects (SDK)
Portal Integration with SAP BusinessObjects (SDK)DMIMarketing
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii FrameworkTuan Nguyen
 

What's hot (14)

MVVM Design Pattern NDC2009
MVVM Design Pattern NDC2009MVVM Design Pattern NDC2009
MVVM Design Pattern NDC2009
 
JavaScript MVC Frameworks: Backbone, Ember and Angular JS
JavaScript MVC Frameworks: Backbone, Ember and Angular JSJavaScript MVC Frameworks: Backbone, Ember and Angular JS
JavaScript MVC Frameworks: Backbone, Ember and Angular JS
 
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.jsAsynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
 
當ZK遇見Front-End
當ZK遇見Front-End當ZK遇見Front-End
當ZK遇見Front-End
 
Angular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page ApplicationAngular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page Application
 
Mvvm basics
Mvvm basicsMvvm basics
Mvvm basics
 
Angular JS Basics
Angular JS BasicsAngular JS Basics
Angular JS Basics
 
SAP Business Objects Software development Kit
SAP Business Objects Software development Kit SAP Business Objects Software development Kit
SAP Business Objects Software development Kit
 
Live Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS FeatuesLive Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS Featues
 
AngularJS - A Powerful Framework For Web Applications
AngularJS - A Powerful Framework For Web ApplicationsAngularJS - A Powerful Framework For Web Applications
AngularJS - A Powerful Framework For Web Applications
 
The dashboarding problem
The dashboarding problemThe dashboarding problem
The dashboarding problem
 
Portal Integration with SAP BusinessObjects (SDK)
Portal Integration with SAP BusinessObjects (SDK)Portal Integration with SAP BusinessObjects (SDK)
Portal Integration with SAP BusinessObjects (SDK)
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii Framework
 
MVVM
MVVMMVVM
MVVM
 

Viewers also liked

Mongo db model relationships with documents
Mongo db model relationships with documentsMongo db model relationships with documents
Mongo db model relationships with documentsDr. Awase Khirni Syed
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesSuresh Patidar
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentSuresh Patidar
 
Latest Trends in Web Technologies
Latest Trends in Web TechnologiesLatest Trends in Web Technologies
Latest Trends in Web Technologiesbryanbibat
 
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
 
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...IEFE
 
Plan Social Media Wawawiwa Design
Plan Social Media Wawawiwa DesignPlan Social Media Wawawiwa Design
Plan Social Media Wawawiwa DesignHumberto Isea
 
World Economic Forum, la grande sciocchezza
World Economic Forum, la grande sciocchezzaWorld Economic Forum, la grande sciocchezza
World Economic Forum, la grande sciocchezzaMassimo Mucchetti
 
100 Text Loans, Text Loans
100 Text Loans, Text Loans100 Text Loans, Text Loans
100 Text Loans, Text Loans100Textloans
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Irfad Imtiaz
 
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...Dr. Oliver Massmann
 
Social by Design REMIXED by Geoff Colon
Social by Design REMIXED by Geoff ColonSocial by Design REMIXED by Geoff Colon
Social by Design REMIXED by Geoff ColonGeoffrey Colon
 
NVM Lensink Gussinklo Makelaardij Presentatie
NVM Lensink Gussinklo Makelaardij PresentatieNVM Lensink Gussinklo Makelaardij Presentatie
NVM Lensink Gussinklo Makelaardij Presentatielensinkgussinklo
 

Viewers also liked (19)

Latest trends in java script show
Latest trends in java script showLatest trends in java script show
Latest trends in java script show
 
Mongo db model relationships with documents
Mongo db model relationships with documentsMongo db model relationships with documents
Mongo db model relationships with documents
 
Knockout js session
Knockout js sessionKnockout js session
Knockout js session
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web Technologies
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
 
Latest Trends in Web Technologies
Latest Trends in Web TechnologiesLatest Trends in Web Technologies
Latest Trends in Web Technologies
 
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
 
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...
د. فوزية اخضر - تطبيق تجربة مدرسة المستقبل الشاملة - المعرض والمنتدى الدولي ل...
 
Plan Social Media Wawawiwa Design
Plan Social Media Wawawiwa DesignPlan Social Media Wawawiwa Design
Plan Social Media Wawawiwa Design
 
Puppetのススメ
PuppetのススメPuppetのススメ
Puppetのススメ
 
World Economic Forum, la grande sciocchezza
World Economic Forum, la grande sciocchezzaWorld Economic Forum, la grande sciocchezza
World Economic Forum, la grande sciocchezza
 
100 Text Loans, Text Loans
100 Text Loans, Text Loans100 Text Loans, Text Loans
100 Text Loans, Text Loans
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )
 
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...
Lawyer in Vietnam Oliver Massmann Trans Pacific Partnership Agreement - Ratif...
 
Social by Design REMIXED by Geoff Colon
Social by Design REMIXED by Geoff ColonSocial by Design REMIXED by Geoff Colon
Social by Design REMIXED by Geoff Colon
 
NVM Lensink Gussinklo Makelaardij Presentatie
NVM Lensink Gussinklo Makelaardij PresentatieNVM Lensink Gussinklo Makelaardij Presentatie
NVM Lensink Gussinklo Makelaardij Presentatie
 
Buddhist Temple Dhammakaya Thai
Buddhist Temple Dhammakaya ThaiBuddhist Temple Dhammakaya Thai
Buddhist Temple Dhammakaya Thai
 
Infoprop (1)
Infoprop (1)Infoprop (1)
Infoprop (1)
 

Similar to Knockout js

Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesQamar Abbas
 
Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fairTech_MX
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patternsallanh0526
 
Using mvvm inside mvc in domain driven design
Using mvvm inside mvc in domain driven designUsing mvvm inside mvc in domain driven design
Using mvvm inside mvc in domain driven designyashar Aliabasi
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSJinkyu Kim
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentationG ABHISEK
 
A Smooth Transition to HTML5
A Smooth Transition to HTML5A Smooth Transition to HTML5
A Smooth Transition to HTML5Chris Bannon
 
Models used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVMModels used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVMAndrei Popa
 
WPF For Beginners - Learn in 3 days
WPF For Beginners  - Learn in 3 daysWPF For Beginners  - Learn in 3 days
WPF For Beginners - Learn in 3 daysUdaya Kumar
 
Angular js up & running
Angular js up & runningAngular js up & running
Angular js up & runningJunaid Baloch
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVCNosheen Qamar
 
software architecture
software architecturesoftware architecture
software architecturearnav gupta
 
Introduction To MVVM
Introduction To MVVMIntroduction To MVVM
Introduction To MVVMBoulos Dib
 

Similar to Knockout js (20)

Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelines
 
Module2
Module2Module2
Module2
 
Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fair
 
Mvvm
MvvmMvvm
Mvvm
 
Adopting MVVM
Adopting MVVMAdopting MVVM
Adopting MVVM
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
Using mvvm inside mvc in domain driven design
Using mvvm inside mvc in domain driven designUsing mvvm inside mvc in domain driven design
Using mvvm inside mvc in domain driven design
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
MVVM and Prism
MVVM and PrismMVVM and Prism
MVVM and Prism
 
MVC architecture
MVC architectureMVC architecture
MVC architecture
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentation
 
A Smooth Transition to HTML5
A Smooth Transition to HTML5A Smooth Transition to HTML5
A Smooth Transition to HTML5
 
Models used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVMModels used in iOS programming, with a focus on MVVM
Models used in iOS programming, with a focus on MVVM
 
WPF For Beginners - Learn in 3 days
WPF For Beginners  - Learn in 3 daysWPF For Beginners  - Learn in 3 days
WPF For Beginners - Learn in 3 days
 
Angular js up & running
Angular js up & runningAngular js up & running
Angular js up & running
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
 
software architecture
software architecturesoftware architecture
software architecture
 
AngularJS is awesome
AngularJS is awesomeAngularJS is awesome
AngularJS is awesome
 
Introduction To MVVM
Introduction To MVVMIntroduction To MVVM
Introduction To MVVM
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 

More from Dr. Awase Khirni Syed

More from Dr. Awase Khirni Syed (7)

Require js training
Require js trainingRequire js training
Require js training
 
Powershell training material
Powershell training materialPowershell training material
Powershell training material
 
Es2015 training material-syedawase
Es2015 training material-syedawaseEs2015 training material-syedawase
Es2015 training material-syedawase
 
R programming groundup-basic-section-i
R programming groundup-basic-section-iR programming groundup-basic-section-i
R programming groundup-basic-section-i
 
Mongo db groundup-0-nosql-intro-syedawasekhirni
Mongo db groundup-0-nosql-intro-syedawasekhirniMongo db groundup-0-nosql-intro-syedawasekhirni
Mongo db groundup-0-nosql-intro-syedawasekhirni
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
 
SycliQ-AgribusinessInfographik001
SycliQ-AgribusinessInfographik001SycliQ-AgribusinessInfographik001
SycliQ-AgribusinessInfographik001
 

Recently uploaded

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 

Recently uploaded (20)

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 

Knockout js

  • 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
  • 2. Code Focused Training Why NOT JQUERY? • Jquery isn’t usually used for complex web apps •No easy way for the UI and the data to communicate •More complex way to interact with the data model •Client Side validations and AJAX calls •DOM Manipulation Library •Limited to Form and UI Interactions © Syed Awase 2015-16 - KnockOut Ground Up! 2
  • 3. What is KnockOut? • Knockout.js is a JavaScript library that enables you to declaratively bind elements against model data with two-way updates happening automatically between your UI and model. • KO is a data-binding library while AngularJS is a full-framework. • Angular uses routes, directives and services , while KO does not. • JavaScript MVVM Framework • MVVM – Model-View-ViewModel • Model – Objects in your business domain • View – User Interface that is visible to the user • ViewModel – code representing data/operations on a UI (Presentation Concerns) • Complimentary to other JavaScript Frameworks • E.g. Jquery, CoffeScript, Prototype, etc. © Syed Awase 2015-16 - KnockOut Ground Up! 3
  • 4. Code Focused Training Knockout © Syed Awase 2015-16 - KnockOut Ground Up! 4 knockout-3.4.0.js http://knockoutjs.com/downloads/knockout-3.4.0.js Referencing in your application Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, Edge, others) http://www.knockmeout.net/
  • 5. Code Focused Training © Syed Awase 2015-16 - KnockOut Ground Up! 5 Knockout “A java script library that helps you to create rich, responsive display and editor UI with a clean underlying data model. Anytime you have section of UI that update dynamically, KO can help you implement it more simply and easily maintainable” Client side data binding library for building data-aware web applications
  • 6. Why Knockout? • Developing a complex and dynamic data-driven web application can be a challenging task. • Keeping a user interface in sync with the underlying data normally involves wiring up a number of event handlers to broker information between the various elements and the data whenever any actions are performed by a user or when new data is loaded. © Syed Awase 2015-16 - KnockOut Ground Up! 6
  • 7. Code Focused Training © Syed Awase 2015-16 - KnockOut Ground Up! 7 DECLARATIVE BINDING Easily associate DOM elements with model data using a concise readable syntax AUTOMATIC UI REFRESH When your data model’s state changes, your UI updates automatically TEMPLATING Quickly generate sophisticated, nested Uis as a function of your model data UI DEPENDENCY TRACKING Implicitly set up chains of relationships between model data, to transform and combine it
  • 8. Code Focused Training Traditional UI Development MODEL VIEW © Syed Awase 2015-16 - KnockOut Ground Up! 8 DOMAIN OBJECTS UI Layout Code behind Update Fetch data
  • 9. Code Focused Training Traditional UI Development Constraints • Difficult to test • Encourages using UI as a data storage • Complex classes and huge amount of code • No Code sharing • Very strong dependency between UI and Logic • Redeisgn requires a lot of effort Why MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 9 Clear responsibilities between the developers and designers
  • 10. Code Focused Training Knockout Architecture © Syed Awase 2015-16 - KnockOut Ground Up! 10 MODEL BUSINESS LOGIC AND DATA VIEW MODEL USER INTERFACE VIEW MODEL PRESENTATION LOGIC JAVASCRIPT REMOTING INSTANT NOTIFICATIONS TWO WAY DATABINDING COMMANDS EXECUTION
  • 11. Code Focused Training Design Patterns and Architectural Guide © Syed Awase 2015-16 - KnockOut Ground Up! 11 Design Patterns are essentially time tested solutions to recurring design problems. SOME DESIGN PATTERNS USED FOR KNOCKOUT MVVM OBSERVER JAVASCRIPTCLOSURE MODULEPATTERN
  • 12. Code Focused Training Presentation Design Pattern © Syed Awase 2015-16 - KnockOut Ground Up! 12 MVVM MVP MVC Model-View-ViewModel Model-View-Presentation Model-View-Controller UI Centric Design Patterns SEPARATION OF CONCERNS CODE REUSABLITY UNIT TESTING SPA DECOUPLING
  • 13. Code Focused Training MVC © Syed Awase 2015-16 - KnockOut Ground Up! 13 VIEW CONTROLLER MODEL Passes Calls to Manipulates Fires Events User Input • Controller contains the logic that alters the model depending on the action triggered by UI. • View is a composite implementation, A view can switch controllers or a single controller can be used by multiple views. View subscribes to changes done to the model • controller manipulates the data but asserting the changes from a view perspective
  • 14. Code Focused Training MVP © Syed Awase 2015-16 - KnockOut Ground Up! 14 VIEW PRESENTER MODEL Passes Calls to Manipulates Fires Events User Input • Controller is replaced by Presenter , it presents the changes done in model back to view. • Presenter here takes the responsibility of not only manipulating model but also updating the view. •MVP Variations •Supervising controller : uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively • Passive View handles this by reducing the behaviour of UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. Allows testing to be focused on the controller with little risk of the problem in the view. Updates
  • 15. Code Focused Training Real World MVC • Controllers are “almost” not reusable • Controllers are large • View is very tight to it’s controller • Controllers are hard to unit test • © Syed Awase 2015-16 - KnockOut Ground Up! 15 MVC VIEW CONTROLLER VIEW MODEL
  • 16. Code Focused Training MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 16 VIEW CONTROLLER VIEW MODEL MODEL VIEWS UNIT TESTS VIEWMODELS MODEL DB ENTITIES Binding, Commands, Data Templates User Controls
  • 17. The Model • The applications stored data • Independent of the UI • Ajax calls to read/write to and from the stored data © Syed Awase 2015-16 - KnockOut Ground Up! 17
  • 18. The View Model • Code representation of the data and operations • Not the UI itself • Pure javascript • Holds unsaved data
  • 19. The View • Visible UI • Displays ViewModel Information • Updates when the State changes • HTML Document with Declarative Bindings + CSS3 Styling.
  • 20. Code Focused Training MVVM • View Model does not need a reference to a VIEW • ViewModel coordinates with one or more models, exposes properties for the view to bind to. • views know about the ViewModel but not the model • ViewModel knows about the Model but not the View • Model Knows about itself • View binds to properties in the ViewModel • .Changes to properties in the ViewModel automatically propogate to the View – no additional code required • Data Changes made in the ViewModel, never the View • More testable than MVC or MVP © Syed Awase 2015-16 - KnockOut Ground Up! 20 VIEW VIEWMODEL MODEL Passes Calls to Manipulates Fires Events User Input
  • 21. Code Focused Training MVVM BENEFITS • Modularity • Decoupling components • Allows each component to be versioned independently • Flexibility • Multiple views for one Model (web front end, desktop front end, mobile front end, etc) • Replace one component (replace data storage from flat file to database) • Maintainability • Only change one component where bug exists, less risk in late changes • Testability • Each component communicates through contract so each component can be unit-tested independently VIEW MODEL ACTS AS A COMPLETE MIRROR OF THE VIEW © Syed Awase 2015-16 - KnockOut Ground Up! 21 VIEW VIEWMODEL MODEL BUSINESS LOGIC PRESENTATION LOGIC UI LOGIC NOTIFICATION DATABINDING
  • 22. Code Focused Training View • UserControl based • XAML • Minimal code behind • Data Context set to the associated VIEWMODEL • No Event Handlers • Databinding pushes the changes from the ViewModel to View and from View to ViewModel • Loosely coupled, can easily replace the view without affecting the view model © Syed Awase 2015-16 - KnockOut Ground Up! 22 ViewModel • Implements INotifyPropertyChanged • Expose Icommand • Handle Validation • Adapter class between the View and the Model • Listen to the Model’s events • Testable Model • Event Based mechanism to signal changes to the ViewModel VIEWMODEL VIEW MODEL
  • 23. Code Focused Training MODEL • Non-visual classes that encapsulate the application’s data and business logic • Can’t see ViewModel or View • Should not contain any use case- specific or user-task-specific behaviour or application logic • Notifies Other components of any state changes • May provide data validation and error reporitng. VIEW MODEL •Non-visual class encapsulates the presentation logic required •Can’t see View ( no direct references) •Coordinates the View’s interactions with the model •May provide data validation and error reporting •Notifies the view of any state changes © Syed Awase 2015-16 - KnockOut Ground Up! 23
  • 24. Code Focused Training VIEW •Visual element defines the controls and their visual layout and styling •Can see all other components •Defines and handles UI visual behaviour, such as animations or transitions •Code behind may contain code that requires direct references to specific UI controls View  ViewModel Interaction Ways Data Binding Commands Notifications © Syed Awase 2015-16 - KnockOut Ground Up! 24
  • 25. Code Focused Training MVP vs.MVC vs.MVVM MVP(Presenter) MVC(Controller) MVVM(ViewModel) View Communicates with the presenter by directly calling functions on an instance of the presenter View sends input events to the controller via a callback or registered handler View binds directly to the View Model The presenter communicates with the view by taking to an interface implemented by the view View receives updates directly from the model without having to go through the controller Changes in view are automatically reflected in ViewModel and viceversa Use where binding via a data context is not possible Use where the connection between the view and the rest of the program is not always available Use where binding via a data context is possible. © Syed Awase 2015-16 - KnockOut Ground Up! 25 e.g. Windows Forms e.g. SmallTalk, ASP.NET MVC e.g. WPF, KO,AngularJS
  • 26. Code Focused Training MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 26 • Enable UI Unit Testing • WPF Line of Business Application • Layers represent Separation of concerns and decoupling • Enables designer – developer workflow • Is a natural pattern given WPF’s rich data binding that promotes loose coupling • Takes full advantage of WPF’s DataTemplates and Commands • UI (view) can be swapped out without touching the UI code
  • 27. Code Focused Training MVVM Advantages • Separation of concerns • Can use unit tests • Designers and developers can work synchronously • Easy to redisgn the UI • Can share code easily Disadvantages •Harder to debug •May affect performance •More files to serve the architecture © Syed Awase 2015-16 - KnockOut Ground Up! 27
  • 28. Code Focused Training DataBinding (State) • Process that establishes a connection between the application UI and application logic • When the data changes its value, the elements that are bound to the data reflect changes automatically • Direction of data flow • One Time: binding update the target with the source data when binding is created • One Way bindings update the target with the source data when the binding is created, and any time the data changes. This is the default mode. • Two Way bindings update both the target and the source when either changes © Syed Awase 2015-16 - KnockOut Ground Up! 28 Dependency Property Property VIEW VIEWMODEL Dependency Object Object BINDING TARGET BINDING SOURCE Provides an easy and efficient method to connect information to a user interface that displays the data
  • 29. Code Focused Training Data Binding Options • Directions of the data flow •One way • Two way • One time • One way to Source •What triggers source updates (LostFocus, PropertyChanged, Explicit, …) •Bind to Objects, Collections, UI Elements • Path, Value Converters, Async, Fallback, StringFormat One Time: the data is set when binding is intialized-mostly used in ReadOnly mode OneWay: Updates the data from source to target, so if source changes the target is notified. Two way: Updates data from source to taget and vice-versa, so if the source changes the target is notified or vice versa © Syed Awase 2015-16 - KnockOut Ground Up! 29
  • 30. ONE-TIME DATA BINDING • When you request one-time data binding, the run-time, using the data source and the specified path, retrieves the source value and initializes the specified target property to that value. • No change occurs subsequently when the source or the target property value is changed. • Two Special Cases – When the DataContext of an element changes, effectively, the data source has changed and therefore the binding performs another one-time transfer – In many cases, the DataContext refers to a collection of objects. When the current object for a collection changes, the databinding performs a one-time transfer. © Syed Awase 2015-16 - KnockOut Ground Up! 30
  • 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.
  • 34. Code Focused Training Commands (Behaviour) •Provide a way to represent actions or operations that can be easily bound to controls in the UI •Encapsulate the actual code that implements the action or operation •Examples: Button Click, List selection changed • OnPropertyChanged method is required to notify binding target properties with change in source • Observable Collection needed for binding lists source •Implementing InotifyPropertyChanged and INotifyCollectionChanged interface © Syed Awase 2015-16 - KnockOut Ground Up! 34
  • 35. Code Focused Training Data Templates • Converts non-visual data into its visual representation •Defines how a view model will be rendered or can modify its default visual representation without changing the underlying object itself or the behavior of the control that is used to display it. Simple datatemplate using HTML Listbox Control © Syed Awase 2015-16 - KnockOut Ground Up! 35
  • 36. Code Focused Training Observer Pattern • A behavioral pattern used to assure consistency between objects • Used to establish relationship between objects at runtime not compile time • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically • Object that changes is called “Subject” • Object that receives updates is called “Object” • Two Approaches • Pull model: Observer invokes method requesting data • Push model: subject passes data to observer as argument at update() Similar to NewsPaper Subscription Publisher publishes and subscribers read Once subscribers unsubscribe, subscribers won’ Once subscribers subscribe again they get to read Publishers are Subject and Subscribers are Observer © Syed Awase 2015-16 - KnockOut Ground Up! 36
  • 37. Code Focused Training Observer Pattern Benefits • Objects are loosely coupled with each other but still communicate properly • Observers can be added/removed at any time • Subject and Observer can belong to different abstraction layers • Subject does not need to know the concrete class of an observer, just that each observer implements the update interface • Observers can be added without modifying the subject Usage • Used when there is one to many relationship between object such as if one object is modified, its dependent objects are to be notified automatically • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. © Syed Awase 2015-16 - KnockOut Ground Up! 37
  • 38. Code Focused Training IIFE • A javascript design pattern which produces a lexical scope, using Javascript’s function scoping. • IIFE is used to avoid variable hoisting from withinblocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined with the function • Emulate privacy © Syed Awase 2015-16 - KnockOut Ground Up! 38
  • 39. Code Focused Training Module Pattern • Help in keeping the units of code for a project both cleanly separated and organized. • originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering. • The module pattern encapsulates “privacy”, state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer’s interface © Syed Awase 2015-16 - KnockOut Ground Up! 39
  • 40. Code Focused Training Revealing Module Pattern • Advantages : • More consistent syntax. • Clear outline of functions and variables which can be accessed publicly which eases readability. • Disadvantages: • If a private function refers to a public function, that public function cannot be overridden if a patch is necessary. The private function will continue to refer to the private implementation and the pattern does not apply to public members, only to functions • Public object members which refer to private variables are also subject to the no-patch rule © Syed Awase 2015-16 - KnockOut Ground Up! 40
  • 41. Code Focused Training Singleton Pattern • It restricts instantiation of a class to a single object. • It can be implemented by creating a class with a method that creates a new instance of the class if one doesnot exist. • In the event of an instance already existing. It simply returns a reference to that object. • They serve as a shared resource namespace which isolate implementation code from global namespace so as to provide a single point of access for functions. © Syed Awase 2015-16 - KnockOut Ground Up! 41
  • 42. Code Focused Training Observer Pattern • A design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state. • When a subject needs to notify observers about something interesting happening. It broadcasts a notification to the observers ( which can include specific data related to the topic of the notification). • When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers. • Encourages us to think hard about the relationships between different parts of our application. • Help in identifying the layers containing direct relationships which could instead be replaced with sets of subjects and observers. • Modular application development, more loosely coupled block to improve code management and reusability. • Dynamic relationships can exist between observers and subjects. • Sometimes, difficult to obtain guarantees that particular parts of our applications are functioning as we may expect. © Syed Awase 2015-16 - KnockOut Ground Up! 42
  • 43. Code Focused Training KO DEBUGGING TOOLS © Syed Awase 2015-16 - KnockOut Ground Up! 43 KO CONTEXT DEBUGGER https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof?hl=en GLIMSE FROM NUGET PACKAGE MANAGER
  • 44. Code Focused Training KO Core © Syed Awase 2015-16 - KnockOut Ground Up! 44
  • 45. Code Focused Training Activating Knockout • Include knockout.js core files using script include tags • Apply Binding using ko.applyBindings • The first parameter says what viewModel object to use with declarative bindings, which is activated. • Optionally, it takes a second parameter to define which part of the document to search for data-bind attributes. Useful in the case of multiple viewModels and associate each viewModel with a different region of a page. © Syed Awase 2015-16 - KnockOut Ground Up! 45 Step 2: Include ko.applyBindings(ViewModel) should be same Step 1: Include knockout.js resource
  • 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
  • 47. KO Observables • JavaScript functions – Not all browsers support javascript getter and setter functions • Internally Knockout JS’s binding observe the Observables • Used to detect and respond to changes on an object • Allows for 2 way data binding, by notifying subscribers about the changes and can automatically detect dependencies. • Can be subscribed to © Syed Awase 2015-16 - KnockOut Ground Up! 47
  • 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.
  • 49. Code Focused Training Explicitly subscribing to observables • To register your own subscriptions to be notified of changes to observables, use subscribe function • Subscribe function takes in 3(three) parameters • Callback – the function that is called whenever the notification happens • Target – defines the value of this in the call back function • Event- name of the event to receive notification for © Syed Awase 2015-16 - KnockOut Ground Up! 49 Advanced Concept
  • 50. Code Focused Training Explicitly subscribing to observables • Dispose: this function is used to terminate a subscription if you wish to. First capture the return value as a variable © Syed Awase 2015-16 - KnockOut Ground Up! 50 Advanced Concept • beforeChange Event: if you want to be notified of the value of an observable before it is about to be changed.
  • 51. Code Focused Training Explicitly subscribing to observables • Dispose: this function is used to terminate a subscription if you wish to. First capture the return value as a variable © Syed Awase 2015-16 - KnockOut Ground Up! 51 Advanced Concept • beforeChange Event: if you want to be notified of the value of an observable before it is about to be changed.
  • 52. Code Focused Training Observables Notify subscribers: notify • Used to notify observable’s subscriber on write, even if the value is the same. • When writing to an observable that contains a primitive value( number, string, boolean or null) the dependencies of the observersable are normally ONLY notified if the value actually changed. Delay/Suppress Change Notification :rateLimit • An observable notifies its subscribers immediately, as soon as it’s changed. But if the observable is changed repeatedly or triggers expensive updates, we may get better performance by limiting or delaying the observable’s change notifications. © Syed Awase 2015-16 - KnockOut Ground Up! 52
  • 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
  • 54. Code Focused Training Prepopulating an ObservableArray • Developers can populate the observable array by passing in some initial items as an array to the constructor © Syed Awase 2015-16 - KnockOut Ground Up! 54
  • 55. Code Focused Training Reading an observableArray • An observableArray is an observable whose value is an array. • The underlying array can be invoked as a function with no parameters. • native javascript array functions can be used to operate on the underlying array. • indexOf: returns an index of the first array item that equals your parameter. • Modify the contents of an array. KO’s methods automatically trigger the dependency tracking mechanisms so that all registered listeners are notified. • Push,Splice ,pop,shift, unshift,reverse, sort, splice © Syed Awase 2015-16 - KnockOut Ground Up! 55
  • 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()
  • 57. Code Focused Training Manipulating an ObservableArray Push(value) • Adds a new item to the end of the array © Syed Awase 2015-16 - KnockOut Ground Up! 57 Pop(value) • Removes the last value from the array and returns it Unshift(value) • Inserts a new item at the beginning of the array
  • 58. Code Focused Training Manipulating an ObservableArray Shift() • Removes the first value from the array and returns it © Syed Awase 2015-16 - KnockOut Ground Up! 58 Reverse(value) •Reverses the order of the array and returns the observableArray( not the underlying array) Sort() • sorts the array contents and returns the observableArray
  • 59. Code Focused Training Manipulating an ObservableArray Splice() • Removes and returns a given number of elements starting from a given index. © Syed Awase 2015-16 - KnockOut Ground Up! 59 Remove • removes all the values that equal someItem and returns them as an array RemoveAll • removes all values that equal a value and returns them as an array.
  • 60. Code Focused Training Manipulating an ObservableArray Destroy() • Finds any objects in the array that equal someItem and gives them a special property called _destroy with value true © Syed Awase 2015-16 - KnockOut Ground Up! 60 DestroyAll() • Finds any objects in the array that are equal to a given object, and gives them a special property called _destroy with a value true Delay/Suppress:rateL imit • Similar to delay and suppressing in observable, they are used to improve performance by limiting or delaying change notifications.
  • 61. Code Focused Training Dependent ObservablesEncapsulate one or more observables Need to manage this pointer
  • 62. Code Focused Training Computed Observables • Functions that are dependent on one or more other observables and will automatically update whenever any of these dependencies change. • Evaluator function is called once each time any of its dependencies change and whatever value it returns will be passed on to the observers such as UI elements or other computed observable © Syed Awase 2015-16 - KnockOut Ground Up! 62
  • 63. Code Focused Training Pure Computed Observables • If your computed observable simply calculates and returns a value based on some observable dependencies, then it’s better to declare it as a ko.pureComputed • Its evaluator does not directly modify other objects or state. • KO can more efficiently manage its re-evaluation and memory use. • KO will automatically suspend or release it if no other code has an active dependency on it. © Syed Awase 2015-16 - KnockOut Ground Up! 63
  • 64. Code Focused Training PureComputed Observable Notify extender • 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. • Use 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. Ratelimit extender • As the dependencies change, a computed observable updates and notifies its subscribers immediately. • To improve the performance by limiting or delaying the computed observable’s updates and notifications. © Syed Awase 2015-16 - KnockOut Ground Up! 64
  • 65. Code Focused Training Determining if Computed Observable • To check if it is a computed observable. • ko.isComputed  returns true or false if it is computed Observable or not • Ko.isObservable  returns true for observables, observable arrays and all computed observables. • Ko.isWritableObservable  returns true for observables, observable arrays, writable computed observables • If you ONLY need to use the compound full name in the UI • KO will create a computed observable internally in order to detect what observables the expression depends on and will automatically dispose it, when the associated elements are removed. © Syed Awase 2015-16 - KnockOut Ground Up! 65 UI Computed Observables
  • 66. Code Focused Training Constructing a computed observable © Syed Awase 2015-16 - KnockOut Ground Up! 66 • 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 your callback functions. • options – An object with further properties for the computed observable A 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 your computed observable. It’s up to you to supply custom logic to handle the incoming values, typically by writing the values to some underlying observable(s)
  • 67. Code Focused Training Constructing a Computed Observable © Syed Awase 2015-16 - KnockOut Ground Up! 67 Constructs a pure computed observable using the given evaluator function and optional object to use for this. Unlike ko.computed, this method doesn’t accept an options parameter. Constructs a pure computed observable using an optionsobject. This accepts the read, write, and owner options
  • 68. Using a computed Observable function Description Dispose() Manually disposes the computed observable, clearing all subscriptions to dependencies 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 subscripts isActive() Returns whether the computed observable may be updated in the future. 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. © Syed Awase 2015-16 - KnockOut Ground Up! 68
  • 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
  • 71.
  • 72. Built-in Bindings: 4.Template © Syed Awase 2015-16 - KnockOut Ground Up! 72 •Traditional JavaScript template in <script> tag JavaScript Templates •Template-less, comment-based syntax Containerless Control flow (Annonymous)
  • 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
  • 75. Code Focused Training KO Bindings  Built-in Bindings Text and Appearance Forms Control Flow Templates  Custom Binding  indispensible tools for any knockout developer and is one of the best extensibility points that knockout has © Syed Awase 2015-16 - KnockOut Ground Up! 75
  • 76. Built-in Bindings: 1.Text and Appearance © Syed Awase 2015-16 - KnockOut Ground Up! 76 • Toggle visibility of the DOM ElementVisible • Text value of DOM elementText • Raw HTML of DOM elementhtml • CSS class(es) of DOM elementCss • Raw style attribute of DOM elementStyle • Any arbitrary attribute of DOM elementAttr
  • 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.
  • 86.
  • 87. Built-in Bindings: 2.FORMS © Syed Awase 2015-16 - KnockOut Ground Up! 87 • Handler invoked when DOM element clickedClick • Handler invoked for arbitrary event on DOM elementEvent • Handler invoked when form submittedSubmit • DOM element enabled if trueEnable • DOM element disabled if trueDisable • Any arbitrary attribute of DOM elementValue • Attached to checkbox and radio buttonchecked • Collection of elements in dropdown or multi-selectoptions • Currently selected item(s) of dropdown or multi-selectselectedOptions • Ensures DOM element has “name” attributeuniqueName
  • 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
  • 104.
  • 105. Built-in Bindings: CONTROL FLOW © Syed Awase 2015-16 - KnockOut Ground Up! 105 • Executes if condition is trueif • Executes if condition is falseifnot • Executes for each item in collectionForeach • Executes for object specified (child models)With
  • 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.
  • 107. The if binding • “if” binding without a container element
  • 110. KO Data Features © Syed Awase 2015-16 - KnockOut Ground Up! 110
  • 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.
  • 112. Component Binding • Injects a specific component into an element • Optional param
  • 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.
  • 121.
  • 122. Custom Bindings • The most important extensibility functionality of knockoutjs
  • 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
  • 132. Array of DOM Nodes
  • 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.
  • 135. Synchronous/Asynchronous loading • Can be set in registration (synchronous :false) • Default is asynchrnous • Sometimes it has no choice.
  • 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
  • 137. Passing parameters • Interpreted like a JavaScript object literal • You can pass arbitrary values of any type
  • 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.
  • 147. Template-Only Components • The object to which the view is bound is the params object passed to the component binding
  • 150.
  • 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.
  • 153. Code Focused Training sak@sycliq.com sak@territorialprescience.com Contact Us Thank You We also provide Code Focused Open House Trainings 153© Syed Awase 2015-16 - KnockOut Ground Up! For code driven trainings Reach out to us +91-9035433124 Current Offerings • AngularJS 1.5.x • TypeScirpt • AngularJS 2 • KnockOutJS • BackBoneJS • Ember JS • Responsive Web Design with Bootstrap, Google Material Design and KendoUI • C# ASP.NET MVC • C# ASP.NET WEB API • C# ASP.NET WCF, WPF • JAVA , SPRING, HIBERNATE • Python , Django • R Statistical Programming INDIA HYDERABAD | BANGALORE | CHENNAI | PUNE OVERSEAS SINGAPORE | MALAYSIA | DUBAI