首页 > 代码库 > Knockout JS

Knockout JS

Client side applications

Introduction: It is built to create dynamic and rich web applications. It is built with MYYM pattern. It serves a single purpose: data binding your ViewModel to your user interface.

 

Components: a view containing HTML and css elements that get data-bound to it. A viewModel that contains the data to bind the view. Telling knowout to perform the date binding.

 

Data binding syntax:

Data binding is accomplished by adding an HTML attribute called data-bind to any HTML element that you want Knockout to replace with information from your ViewModel.

Another scenario is that sometimes an HTML tag does not work. We need multi HTML tags. So Knoukout allows you to specoify data bindings with HTML comments. As below:

 

Example 1-1. Knockout bindings using HTML comments
<!-- ko -->
<!-- /ko -->

Example:

技术分享

 

ViewModel:
Knockout does not limit you to a single ViewModel per view. 
A ViewModel can be any type of JavaScript variable.

Basic ViewModle:
var myFirstViewModel = {
    name: ‘Steve Kennedy‘
};

Object Oriented Viewmodel:
We can create object and then write function inside of the object. Therefore, we can access my name property without calling my class property directly from elsewhere in my code.

Example:
技术分享

Self = this, it provides me a property in my class that I can use inside methods of my class and easily reference other methods or properties in my class.


ViewModel with parameters:


技术分享

 


Data bingind In and out:
Bind text:
Bind function
Bind Html attributes, css classes, css styles:
  Html Attribute:
<p data-bind="attr: { id: ‘myCustomId‘ }" This p tag has an id data bound to it.</p>
 Css class & style: <p data-bind="style: { marginBottom: 0, paddingBottom: ‘1em‘ }, css: ‘myClass‘">This text has custom styles and a CSS class.</p>
Data bind with conditions.


  




Knockout JS