Knockout js

153
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

Transcript of Knockout js

Page 1: Knockout js

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

Page 2: Knockout js

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

Page 3: Knockout js

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

Page 4: Knockout js

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/

Page 5: Knockout js

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

Page 6: Knockout js

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

Page 7: Knockout js

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

Page 8: Knockout js

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

Page 9: Knockout js

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

Page 10: Knockout js

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

Page 11: Knockout js

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

JAVASCRIPT CLOSURE

MODULE PATTERN

Page 12: Knockout js

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

Page 13: Knockout js

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

Page 14: Knockout js

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

Page 15: Knockout js

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

Page 16: Knockout js

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

Page 17: Knockout js

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

Page 18: Knockout js

The View Model

• Code representation of the data and operations

• Not the UI itself

• Pure javascript

• Holds unsaved data

Page 19: Knockout js

The View

• Visible UI

• Displays ViewModel Information

• Updates when the State changes

• HTML Document with Declarative Bindings + CSS3 Styling.

Page 20: Knockout js

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

Page 21: Knockout js

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

NO

TIF

ICA

TIO

N

DA

TA

BIN

DIN

G

Page 22: Knockout js

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

Page 23: Knockout js

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

Page 24: Knockout js

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

Page 25: Knockout js

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

Page 26: Knockout js

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

Page 27: Knockout js

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

Page 28: Knockout js

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

Page 29: Knockout js

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

Page 30: Knockout js

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

Page 31: Knockout js

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

Page 32: Knockout js

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.

Page 33: Knockout js

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.

Page 34: Knockout js

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

Page 35: Knockout js

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

Page 36: Knockout js

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

Page 37: Knockout js

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

Page 38: Knockout js

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

Page 39: Knockout js

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

Page 40: Knockout js

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

Page 41: Knockout js

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

Page 42: Knockout js

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

Page 43: Knockout js

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

Page 44: Knockout js

Code Focused Training

KO Core

© Syed Awase 2015-16 - KnockOut Ground Up! 44

Page 45: Knockout js

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

Page 46: Knockout js

Code Focused Training

3 Types of KO Observables

• Used for view model properties Observable

• Used for collections Observable

arrays

• Encapsulate one or more other observables

Dependent observables

Page 47: Knockout js

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

Page 48: Knockout js

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.

Page 49: Knockout js

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

Page 50: Knockout js

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.

Page 51: Knockout js

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.

Page 52: Knockout js

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

Page 53: Knockout js

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

Page 54: Knockout js

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

Page 55: Knockout js

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

Page 56: Knockout js

Code Focused Training

Observable array methods

• Returns zero-based index of item List.indexOf(“value”)

• Returns items between start/end index List.slice(2,4)

• Adds new item to end List.push(“value”)

• Removes last item List.pop()

• Inserts item at beginning List.unshift(“value”)

• Reverses order List.reverse()

• Sorts the items List.sort()

• Removes specified item List.remove(item)

• Removes all items List.removeAll()

Page 57: Knockout js

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

Page 58: Knockout js

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

Page 59: Knockout js

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.

Page 60: Knockout js

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

• Similar to delay and suppressing in observable, they are used to improve performance by limiting or delaying change notifications.

Page 61: Knockout js

Code Focused Training

Dependent Observables Encapsulate one or more observables

Need to manage this pointer

Page 62: Knockout js

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

Page 63: Knockout js

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

Page 64: Knockout js

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

Page 65: Knockout js

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

Page 66: Knockout js

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)

Page 67: Knockout js

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

Page 68: Knockout js

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

Page 69: Knockout js

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

Page 70: Knockout js

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.

getDependenciesCount()

returns the number of dependencies of the computed observable detected so far during the current evaluation

Page 71: Knockout js
Page 72: Knockout js

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)

Page 73: Knockout js

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.

Page 74: Knockout js

Binding Values

• Can be a value, variable, literal or any type of JavaScript expression

Page 75: Knockout js

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

Page 76: Knockout js

Built-in Bindings: 1.Text and Appearance

© Syed Awase 2015-16 - KnockOut Ground Up! 76

• Toggle visibility of the DOM Element Visible

• Text value of DOM element Text

• Raw HTML of DOM element html

• CSS class(es) of DOM element Css

• Raw style attribute of DOM element Style

• Any arbitrary attribute of DOM element Attr

Page 77: Knockout js

The visible binding

• Causes the associated DOM element to become hidden or visible according to the value you pass to the binding.

Page 78: Knockout js

The visible binding

• Using functions and expressions to control element visibility

– We can use javascript function or arbitrary javascript expression as the parameter value.

Page 79: Knockout js

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

Page 80: Knockout js

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.

Page 81: Knockout js

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.

Page 82: Knockout js

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

Page 83: Knockout js

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.

Page 84: Knockout js

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

Page 85: Knockout js

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.

Page 86: Knockout js
Page 87: Knockout js

Built-in Bindings: 2.FORMS

© Syed Awase 2015-16 - KnockOut Ground Up! 87

• Handler invoked when DOM element clicked Click

• Handler invoked for arbitrary event on DOM element Event

• Handler invoked when form submitted Submit

• DOM element enabled if true Enable

• DOM element disabled if true Disable

• Any arbitrary attribute of DOM element Value

• Attached to checkbox and radio button checked

• Collection of elements in dropdown or multi-select options

• Currently selected item(s) of dropdown or multi-select selectedOptions

• Ensures DOM element has “name” attribute uniqueName

Page 88: Knockout js

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

Page 89: Knockout js

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.

Page 90: Knockout js

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

Page 91: Knockout js

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

Page 92: Knockout js

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.

Page 93: Knockout js

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

Page 94: Knockout js
Page 95: Knockout js

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.

Page 96: Knockout js

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

Page 97: Knockout js

$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

Page 98: Knockout js

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

Page 99: Knockout js

$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

Page 100: Knockout js

$data

• View model object in the current context

• In $root context, $data and $root are the same

• Useful to reference the view model itself.

Page 101: Knockout js

$index

• Only available within foreach bindings

• Zero-based index of the current array entry

• Observable and updated

Page 102: Knockout js

$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

Page 103: Knockout js

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

Page 104: Knockout js
Page 105: Knockout js

Built-in Bindings: CONTROL FLOW

© Syed Awase 2015-16 - KnockOut Ground Up! 105

• Executes if condition is true if

• Executes if condition is false ifnot

• Executes for each item in collection Foreach

• Executes for object specified (child models) With

Page 106: Knockout js

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.

Page 107: Knockout js

The if binding

• “if” binding without a container element

Page 108: Knockout js

Iterating over an array

Page 109: Knockout js

Add/remove records

Page 110: Knockout js

KO Data Features

© Syed Awase 2015-16 - KnockOut Ground Up! 110

Page 111: Knockout js

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.

Page 112: Knockout js

Component Binding

• Injects a specific component into an element

• Optional param

Page 113: Knockout js

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)

Page 114: Knockout js
Page 115: Knockout js

Templating?

• Templating gives us a simple and elegant way to build professional looking user interface structures

• Templating Type

–Native templating

–String Based Templating

Page 116: Knockout js

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.

Page 117: Knockout js

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.

Page 118: Knockout js

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

Page 119: Knockout js

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.

Page 120: Knockout js

Underscore Template Engine

Page 121: Knockout js
Page 122: Knockout js

Custom Bindings

• The most important extensibility functionality of knockoutjs

Page 123: Knockout js

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.

Page 124: Knockout js

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.

Page 125: Knockout js

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

Page 126: Knockout js
Page 127: Knockout js

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.

Page 128: Knockout js

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.

Page 129: Knockout js

Specifying a template

• Existing Element ID

• Existing Element instance

• String of MARKUP

• Array of DOM Nodes

• Document Fragment

• AMD Module

Page 130: Knockout js

Element Instance

Page 131: Knockout js

String of MARKUP

Page 132: Knockout js

Array of DOM Nodes

Page 133: Knockout js

AMD MODULE (e.g.RequireJS)

Page 134: Knockout js

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.

Page 135: Knockout js

Synchronous/Asynchronous loading

• Can be set in registration (synchronous :false)

• Default is asynchrnous

• Sometimes it has no choice.

Page 136: Knockout js

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

Page 137: Knockout js

Passing parameters

• Interpreted like a JavaScript object literal

• You can pass arbitrary values of any type

Page 138: Knockout js

Component Binding

Page 139: Knockout js

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

Page 140: Knockout js

Component Life Cycle

• Component loaders supply vm and template 1

• Template is cloned and injected 2

• Vm is instantiated 3

• Vm is bound to view 4

• Component is active 5

• Component is torn down and view model is disposed 6

Page 141: Knockout js

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

Page 142: Knockout js

2.Template is Cloned

• Template is cloned and injected into the container element

• Any existing content is removed and discarded

Page 143: Knockout js

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

Page 144: Knockout js

4. ViewModel is bound to view

• If no viewmodel, then view is bound to any params supplied to the component binding

Page 145: Knockout js

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

Page 146: Knockout js

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.

Page 147: Knockout js

Template-Only Components

• The object to which the view is bound is the params object passed to the component binding

Page 148: Knockout js

Containerless Components

• Passing Params

Page 149: Knockout js

Passing markup

Page 150: Knockout js
Page 151: Knockout js

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.

Page 152: Knockout js

EMIT JSON DATA

Page 153: Knockout js

Code Focused Training

[email protected]

[email protected]

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