knockout.js

23
Knockout.js Simplify dynamic JavaScript UIs by applying the Model-View-ViewModel(MVVM)

Upload: a-man-on-quest

Post on 11-May-2015

2.731 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Knockout.js

Knockout.jsSimplify dynamic JavaScript UIs by applying

the Model-View-ViewModel(MVVM)

Page 2: Knockout.js

What is Knockout.js ?Knockout is a JavaScript library that helps us

to create rich, responsive and dynamic display with a clean underlying data model.

Page 3: Knockout.js

Key pointsFree, open source (MIT license)Pure JavaScript — works with any web

frameworkSmall & lightweight — 40kb minified

... reduces to 14kb when using HTTP compression

No dependenciesSupports all mainstream browsers

IE 6+, Firefox 2+, Chrome, Opera, Safari (desktop/mobile)

Fully documented API docs, live examples, and interactive tutorials included

Page 4: Knockout.js

Features it offersDeclarative Bindings

Easily associate DOM elements with model data using a concise, readable syntax

Automatic UI Refresh Whenever data model's state changes, UI updates

automatically

Dependency Tracking Implicitly set up chains of relationships between model data, to

transform and combine it

Templating Quickly generate sophisticated, nested UIs as a function of

your model data

Page 5: Knockout.js

Is it different from jQuery or any other javascript framework?jQuery/js Frameworks KnockoutBasically a replacement for

the clunky, inconsistent DOM APIs we had to put up with in the past.

A low-level way to manipulate elements and event handlers in a web page.

Knockout provides a complementary, high-level way to link a data model to a UI.

Note: Both can be used in solution seamlessly.

Page 6: Knockout.js

Core FeaturesObservables and dependency trackingDeclarative bindingsTemplating

Page 7: Knockout.js

Let’s Bind//Javascript Code<script> var myViewModel = {     personName: ‘Vivek',     personAge: 27 };

//Restrict the binding to this span only ko.applyBindings(myViewModel, document.getElementById(‘name'));</script>

//HTML CodeThe name is <span id=“name” data-bind="text: personName"></span>

Page 8: Knockout.js

ObservablesLast example was the basic one as it was kind

of one way binding i.e. the ViewModel’s property will show up in UI but if we want that on every change of property in ViewModel the UI should also get reflected then make it observable property:

var myViewModel = {

    personName: ko.observable(Vivek'),

    personAge: ko.observable(27)

};

Page 9: Knockout.js

Explicitly subscribing to observablesIn the last example if we want to listen the

value change of personName property:

myViewModel.personName.subscribe(function(newValue) {

    alert("The person's new name is " + newValue);

});

If you want to terminate the subscription:var subscription = myViewModel.personName.subscribe(function(newValue) {

    alert("The person's new name is " + newValue);

});

subscription.dispose(); // no longer want notifications

Page 10: Knockout.js

Computed Observablesfunction myViewModel() {

    this.firstName = ko.observable(‘Johnny');

    this.lastName = ko.observable(‘English');

}

Here in above ViewModel if you want to show Full name which you want it to be dynamic(observable) i.e. full name changes with a change in first/last name

function myViewModel() {

    this.firstName = ko.observable(‘Johnny');

    this.lastName = ko.observable(‘English');

this.fullName = ko.computed(function(){

return this.firstName() +” “+ this.lastName();

}, this);

}

//HTML Code

The name is <span data-bind="text: fullName"></span>

Page 11: Knockout.js

BindingsTypes of binding available:

visible, text, html, css, style, attr

“visible”<div data-bind="visible: shouldShowMessage">

    You will see this message only when "shouldShowMessage" holds a true value.

</div>

<script type="text/javascript">

    var viewModel = {

        shouldShowMessage: ko.observable(true) // Message initially visible

    };

    viewModel.shouldShowMessage(false); // ... now it's hidden

    viewModel.shouldShowMessage(true); // ... now it's visible again

</script>

Page 12: Knockout.js

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

 

<script type="text/javascript">

    var viewModel = {

        myMessage: ko.observable() // Initially blank

    };

    viewModel.myMessage("Hello, world!"); // Text appears

</script>

“html”<div data-bind=“html: details"></div>

 

<script type="text/javascript">

    var viewModel = {

        details: ko.observable() // Initially blank

    };

viewModel.details("<em>For further details, view the report <a href='report.html'>here</a>.</em>"); // HTML content appears

</script>

Page 13: Knockout.js

“css”<div data-bind="css: { error: limit() < 0 }">   Range Information</div><script type="text/javascript">    var viewModel = {        limit: ko.observable(100) //say a valid range is 0-100    };    viewModel.limit(-10); // Causes the “error" class to be applied</script>

“style”<div data-bind="style: { error: limit() < 0 ? ‘red’ :’black’}">   Range Information</div><script type="text/javascript">    var viewModel = {        limit: ko.observable(100) //say a valid range is 0-100    };    viewModel.limit(-10); // Causes the DIV’s content to go red</script>

Page 14: Knockout.js

“attr”<a data-bind="attr: { href: url, title: details }">    Report</a> <script type="text/javascript">    var viewModel = {        url: ko.observable("year-end.html"),        details: ko.observable("Report including final year-end statistics")    };</script>

For custom attributes you can write:<a data-bind="attr: { ‘custom-attribute’: customvValue}">    Report</a>Note: attribute here is enclosed in quotes.

Page 15: Knockout.js

Control Flow Statements“foreach”“if”“ifnot”“with”

Page 16: Knockout.js

“foreach”<table>    <thead>        <tr><th>First name</th><th>Last name</th></tr>    </thead>    <tbody data-bind="foreach: people">        <tr>            <td data-bind="text: firstName"></td>            <td data-bind="text: lastName"></td>        </tr>    </tbody></table>

Page 17: Knockout.js

</script>function myViewModel() {    var self = this;     self.people = ko.observableArray([ //The change in the array will reflect in the UI        { name: 'Bert' },        { name: 'Charles' },        { name: 'Denise' }    ]);} ko.applyBindings(new myViewModel());

</script>

Page 18: Knockout.js

“if”<div data-bind="if: displayMessage">Message is being displayed.</div><script>

ko.applyBindings({    displayMessage: ko.observable(false)});

</script>

“ifnot”<div data-bind="ifnot: displayMessage">Message is being

displayed.</div><script>

ko.applyBindings({    displayMessage: ko.observable(false)});

</script>

Note: similar to <div data-bind="if: !someProperty()">...</div>

Page 19: Knockout.js

“with” Creates a new binding context, so that descendant elements are bound in

the context of a specified object.

<h1 data-bind="text: city"> </h1><p data-bind="with: coords">    Latitude: <span data-bind="text: latitude"> </span>,    Longitude: <span data-bind="text: longitude"> </span></p> <script type="text/javascript">    ko.applyBindings({        city: "London",        coords: {            latitude:  51.5001524,            longitude: -0.1262362        }    });</script>

Page 20: Knockout.js

Form fields bindingClick bindingEvent BindingSubmit BindingEnable BindingDisable BindingValue BindingHasFocus BindingChecked BindingOptions BindingSelectedOptions BindingThe uniqueName binding

Page 21: Knockout.js

Template BindingNative templating: Uses HTML markup contained

in the body only. Built into knockout and doesn’t require any external library.

String-based templating: Knockout passes the model values to the external template engine and inject the resulting markup back into our document. Similar to what we were doing it till now using jQuery template. Other library being Underscore template engines.

Page 22: Knockout.js

<h2>Participants</h2>Here are the participants:<div data-bind="template: { name: 'person-template', data: buyer }"></div><div data-bind="template: { name: 'person-template', data: seller }"></div> <script type="text/html" id="person-template">    <h3 data-bind="text: name"></h3>    <p>Credits: <span data-bind="text: credits"></span></p></script> <script type="text/javascript">     function MyViewModel() {         this.buyer = { name: 'Franklin', credits: 250 };         this.seller = { name: 'Mario', credits: 5800 };     }     ko.applyBindings(new MyViewModel());</script>

Native Templating

Page 23: Knockout.js

<h1>People</h1><div data-bind="template: 'peopleList'"></div> <script type="text/html" id="peopleList">    {{each people}}        <p>            <b>${name}</b> is ${age} years old        </p>    {{/each}}</script> <script type="text/javascript">    var viewModel = {        people: ko.observableArray([            { name: 'Rod', age: 123 },            { name: 'Jane', age: 125 },        ])    }    ko.applyBindings(viewModel);</script>

String-based Templating