knockout js

24
KnockoutJS

Upload: andrey-kolodnitsky

Post on 15-Jul-2015

96 views

Category:

Technology


0 download

TRANSCRIPT

KnockoutJS

Key features

• Declarative bindings

• Automatic UI refresh

• Dependency tracking

• Templating

• Free

• Pure JavaScript with no dependencies

• Small (54 kb minified)

• Fully documented

In 2 words

• Provides easy way to link data model

and UI by exposing MVVM pattern

MVVM

• Model-View-ViewModel

• It’s a pattern

• It’s all about separation of concerns

• In our case:

– Model – represents the data

– View – HTML presentation layer

– ViewModel – Holds the behavior and

data for the view

How model is linked to the UI and vice versa?

• 2 way data binding

What is 2 way data binding?

• It’s a kind of magic

• It’s real fun

• It’s automatic way of synchronization

of data between model and view

One way data binding

Two way data binding

Let’s take a look at example

http://jsfiddle.net/Lo1xecse/

How 2 way data binding is achieved?

• Observables – are special JS

objects that can notify of changes

and can detect dependencies

What observables are provided?

• Observable

• Computed

• ObservableArray

Observable example

http://jsfiddle.net/Lo1xecse/1/

Computed example

http://jsfiddle.net/Lo1xecse/2/

http://jsfiddle.net/Lo1xecse/3/

Observable arrays

http://jsfiddle.net/Lo1xecse/4/

Control flow bindings

• foreach – iterates through collection

• if

• ifnot

• with – changes context

Binding context

• $root – root VM

• $parent – parent VM

• $data – current VM

• $index – current index in foreach

Interactive bindings

• click – calls VM method when model is

clicked

• value – form element value

• enable – enabling disabling element

• event – calls specified event when

occurs

• And many others…

Templates

• By default inline

http://jsfiddle.net/Lo1xecse/4/

• But still can be injected

http://jsfiddle.net/Lo1xecse/5/

Custom bindings

• Allows to create your own bindings

and link them to elements

• Add to ko.bindingHandlers your own

object and use it in markup

• http://jsfiddle.net/Lo1xecse/6/

Developing SPA

• Perfectly suits for small or medium

level applications

• Does not have routing so it needs to

be added by yourself (sammy)

• Does not have ability to load

dynamically templates (can be easily

implemented)

Pros

• Free

• Lightweight

• Data binding is awesome

• Very small learning curve

• Perfectly suits for small to medium

level SPA

What’s next?

Let’s create sample application.

User management page (CRUD)

With JQuery, RequireJS, Knockout

Homework

• Pass knockout tutorial

• Implement users app with

knockout