Knockout. js simple and practical tutorial 1. knockout. js

Source: Internet
Author: User

Knockout. js simple and practical tutorial 1. knockout. js

The first time I came into contact with knockout was more than a year ago. At that time, I took over a project from another person and used knockout to bind data. Then you start to learn knockout. This is also used multiple times in subsequent projects. I encountered some difficulties when I started learning for the first time. So I want to write a relatively beginner tutorial to let everyone know and use knockout. In fact, all the usage methods can be viewed in the documentation on the official website. I am here for those who are not used to reading English documents and are just getting started (PS: bad habit to change, because most documents are in English)

No more nonsense. First, I will briefly describe knockout. js is a lightweight MVVM front-end framework. Simply put, it is used to bind data. Its advantage is that if the data source sends a change, it will automatically refresh the data without manual re-binding. The second advantage is the separation of front-end and back-end code, that is, the MVVM idea. Take ASP. NETMVC as an example. In ASP. in NETMVC, if you need to bind data, what should you do? In the past, we used to send the data to viewdata, and then bind it to the foreground using the razor syntax, that is, bind it through the background code. However, the problem is that you need to add various judgments to remove the blank content. Otherwise, the annoying yellow pages will appear. In addition, you cannot asynchronously refresh the page, and you do not need to consider this issue through knockout, which is the benefit of MVVM. I only need to process json data. There are so many introductions. For other benefits, please feel free to use them.

Before using knockout, you need to understand several concepts.

First, Viewmodel and MVC model are not a thing. This viewmodel is a JS object.

Something like this

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

 

You can declare multiple VM models on one page. But I do not recommend this. The reason will be discussed later.

The basic syntax for knockout binding is

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

Bind the property data-bind to the tag. Supports text binding, html binding, property binding, and css binding. I will not list the students who want to know details can go to the official website to view the address is http://knockoutjs.com/documentation/introduction.html

The knockout syntax is very flexible. Many syntaxes when you don't know how to write them, you can try it by writing the background code syntax at ordinary times. Of course, it is still the fastest way to check official documents.

The last step of the above binding is

ko.applyBindings(myViewModel);

Bind the model to the document. Of course, you can also bind the data to a specific document object, such as div, table, and other syntaxes and the above types.

Ko. applyBindings (myViewModel, document. getElementById ("Specific dom object id "));

 

The above binding method is relatively dead. Because data is written to death, how can we dynamically bind it? That is, when the data source changes the automatic page update, we will introduce the observables syntax. In short, the observables is automatically bound. If the metadata changes, it automatically updates itself. The following is a column

// Current Model var ViewModel = function (first, last) {this. firstName = ko. observable (first); this. lastName = ko. observable (last); this. fullName = ko. pureComputed (function () {// when the firstname changes, the model will be updated. return this. firstName () + "" + this. lastName () ;}, this) ;}; ko. applyBindings (new ViewModel ("Planet", "Earth"); // you can specify and bind an initial value.

This is the code for creating models and binding models in JS. You can see it clearly. The general meaning of a brief description is to create a model. The model has two or three fields, two of which are automatically bound to the ID, which means that the model will be automatically updated when the model is changed. That means. The third field is automatically updated. The binding code is provided below.

<p>First name: <input data-bind="value: firstName" /></p><p>Last name: <input data-bind="value: lastName" /></p>

In this address http://jsfiddle.net/rniemeyer/bxfXd/ can debug this code. I believe that after reading this code, you can understand what is automatic data update.

In general, we also need to bind events to dom objects on the page. So how is event binding in knockout? The following is an example of a piece of code.

var ClickCounterViewModel = function() {    this.numberOfClicks = ko.observable(0);     this.registerClick = function() {        this.numberOfClicks(this.numberOfClicks() + 1);    };     this.resetClicks = function() {        this.numberOfClicks(0);    };     this.hasClickedTooManyTimes = ko.pureComputed(function() {        return this.numberOfClicks() >= 3;    }, this);}; ko.applyBindings(new ClickCounterViewModel());

The above code. I believe everyone can understand it. The simple logic is used to count the number of clicks. If we look at it with an object-oriented approach. That is to say, an "object" has various attributes, such as name, gender, and so on. There are also various behaviors, such as eating and walking. This is called the behavior of objects. Here, the attribute object is replaced by the ko (in the Post-knockout text) field, and the object behavior is the js event in ko. Binding ko can be called object initialization. the above explanations are to help readers better understand the meaning of ko's model. After talking about so many events, how can we bind events? The code bound to the dom is as follows:

<div>You've clicked <span data-bind='text: numberOfClicks'>&nbsp;</span> times</div> <button data-bind='click: registerClick, disable: hasClickedTooManyTimes'>Click me</button> <div data-bind='visible: hasClickedTooManyTimes'>    That's too many clicks! Please stop before you wear out your fingers.    <button data-bind='click: resetClicks'>Reset clicks</button></div>

The address http://jsfiddle.net/rniemeyer/3Lqsx/ for debugging is also given above

 

I believe that after reading the above content. You have some knowledge about ko. The following describes how to bind a json object. This is also the most widely used method. Here is a general example based on the previous binding method,

In the following example, there are binding events, binding simple data and array sets.

The first step is to create a model object.

Var SimpleListModel = function (items) {this. items = ko. observableArray (items); this. itemToAdd = ko. observable (""); this. addItem = function () {if (this. itemToAdd ()! = "") {This. items. push (this. itemToAdd (); // Insert the text you entered into the array. this. itemToAdd (""); // clear the text content of the itemtoadd field }}. bind (this) ;}; ko. applyBindings (new SimpleListModel (["Alpha", "Beta", "Gamma"]); // You can initialize it here. You can directly drop the json data you have obtained.

 

When creating this model object, I declare the type of the first attribute as ko. observableArray (). The above example uses ko. the only difference between them is whether to bind a single character or an array set. Everything else is the same. If you treat the VM as an object, you can better understand it. It is equivalent to the field type in the object. One is int and the other is list <int>.

The code for binding the dom is provided below.

<form data-bind="submit: addItem">    New item:    <input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />    <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>    <p>Your items:</p>    <select multiple="multiple" width="50" data-bind="options: items"> </select></form>

 

Debug address http://jsfiddle.net/rniemeyer/bxfXd/

I believe you can easily understand this binding after reading the previous content. It can be seen from this that the ko syntax is very flexible. You can write data at will. This is also the advantage of the scripting language.

We can see that everyone here should have a certain understanding of ko's overall and simple use, and there will certainly be a lot of questions (you can leave a message below to raise it ). However, this is not the end. In the future, I will continue to complete this series of ko tutorials. I have compiled many of these content based on official documents. I also have some understanding in it. If you have any shortcomings, please forgive me.

 

Knockout. js official http://knockoutjs.com/downloads/index.html


Simple and easy-to-understand Cool Edit Pro V21 tutorial

Seek cool edit pro usage tutorial (recording dry sound, simple cutting) Cutting: Cut, read paste, it is best to give a picture, tell me how to use the buttons on the entire interface. Send you a graphic tutorial. Here is a tutorial and

How can I output 1 to 100 with JS loop statements? Simple Method

For (var I = 1; I <= 100; I ++) {alert (I); // dialog box output} the syntax of JS is similar to that of other programming languages.
 

Related Article

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: info-contact@alibabacloud.com 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.