Simple usage of knockout

Source: Internet
Author: User
1 knockout Introduction

Knockout is a lightweight UI class library that simplifies the Javascript front-end UI by applying the mvvm mode.

Knockout is a javascript class library based on the data model that helps you create rich texts, display responses, and edit user interfaces. If your UI needs to be updated automatically at any time (for example, updates depend on user behavior or changes to external data sources), Ko can help you easily implement and maintain it easily.

Knockout has the following four important concepts:

1. Declarative bindings: it is easy to associate model data to DOM elements using concise and easy-to-read syntax.

2. Automatic UI Refresh: when your model state changes, the UI is automatically updated.

3. Dependency tracking: establishes an implicit relationship between your model data for transformation and joint data.

4. templating: quickly compile a complex and nested UI for your model data.

Abbreviation: Ko


2. Getting Started

1. Create a viewmodel without monitoring attributes

To create a view model, you only need to declare any JavaScript Object. For example:

var myViewModel = {    personName: ‘Bob‘,    personAge: 123};


Bind the viewmodel to HTML code. For example, the following code displays the personname value.

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


To activate knockout, add the following <SCRIPT> code block:



2. Create a view model with monitoring attributes

Monitoring attribute observables
Now you know how to create a simple view model and display its attributes through binding. However, an important feature of Ko is that it can automatically update your interface when your view model changes. How does Ko know when your view model is partially changed? The answer is: You need to declare your model attribute as observable, because it is a very special JavaScript objects that can notify subscribers of its changes and automatically detect related dependencies.
For example, change the view model in the preceding example to the following code:

var myViewModel = {    personName: ko.observable(‘Bob‘),    personAge: ko.observable(123)};


You do not need to modify the view-all data-bind syntax. The difference is that it can monitor the changes. When the value changes, the view is automatically updated.

3. Use knockout

In our system, each page defines a viewmodel, which stores all the data on the page, reads data through Ajax, and fills in the viewmodel.

Suppose we have a class page, which is defined as the next viewmodel:

// Define the view var classviewmodel = {classid: Ko. observable (), // class ID classname: Ko. observable (), // class name classmastername: Ko. observable (), // class teacher students: Ko. observablearray (), // bind an array to the list of class students}; $ (document ). ready (function () {// bind Ko. applybindings (classviewmodel); // Add Student Information $ ("# addstudent "). on ("click", function () {var OBJ = new object (); obj. stuname = "Yang Guo"; obj. stusex = "male"; obj. stuage = "100"; classviewmodel. students. push (OBJ) ;};}); // Ajax obtains class information and assigns a value to viewmodel $. post ("/home/getclassinfo", function (data) {classviewmodel. classid (data. classid); // class ID assignment, which is directly mapped to the classviewmodel interface. classname (data. classname); classviewmodel. classmastername (data. classmastername); // obtain student information for (VAR I = 0; I <data. stulist. length; I ++) {var OBJ = new object (); obj. stuname = data. stulist [I]. stuname; obj. stusex = data. stulist [I]. stusex; obj. stuage = data. stulist [I]. stuage; classviewmodel. students. push (OBJ );}})


Corresponding HTML code:

<SCRIPT src = "~ /Scripts/jquery-1.7.1.min.js "> </SCRIPT> <SCRIPT src = "~ /Scripts/knockout-3.2.0.js "> </SCRIPT> <SCRIPT src = "~ /Scripts/viewmodel/myclassviewmodel. js "> </SCRIPT> <H2> myclass </H2> <! -- ATTR property binding --> Class Name: <span data-bind = "text: classid, ATTR: {'id ': classid} "> </span> <br/> class teacher: <span data-bind =" text: classname "> </span> <br/> <Table> <tr> <TH> name </Th> <TH> gender </Th> <TH> age </Th> </tr> <! -- Bind students cyclically --> <tbody data-bind = "foreach: Students"> <tr> <TD data-bind = "text: stuname "> </TD> <TD data-bind =" text: stusex "> </TD> <TD data-bind =" text: stuage "> </TD> </tr> </tbody> </table> <br/> <input type =" button "id =" addstudent "value =" add student "/>


Background Data:

Public class homecontroller: controller {public actionresult index () {viewbag. Message = "modify this template to quickly start your ASP. net mvc application. "; Return view () ;}public actionresult about () {viewbag. Message =" your application description page. "; Return view () ;}public actionresult contact () {viewbag. Message =" your contact information page. "; Return view ();} public actionresult myclass () {return view ();} public jsonresult getclassinfo () {myclass = new myclass (); myclass. classid = "jsj001"; myclass. classname = "Computer Class 1"; myclass. classmastername = "long"; myclass. stulist = new list <students> (); myclass. stulist. add (new students () {stuage = "10", stuname = "Zhang San", stusex = "Warm male"}); myclass. stulist. add (new students () {stuage = "20", stuname = "Li Si", stusex = "Warm male"}); myclass. stulist. add (new students () {stuage = "30", stuname = "Wang Wu", stusex = "Warm male"}); Return JSON (myclass );}} public class myclass {// <summary> // class ID /// </Summary> Public String classid {Get; set ;} /// <summary> /// class name // </Summary> Public String classname {Get; set ;} /// <summary> // class teacher name // </Summary> Public String classmastername {Get; set;} public list <students> stulist {Get; set ;}} public class students {Public String stuname {Get; set;} Public String stusex {Get; set;} Public String stuage {Get; Set ;}}

Simple usage of knockout

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.