Knockoutjs is an MVVM framework implemented in JavaScript. It mainly has the following functions:
1. Declarative bindings
2. Observables and dependency tracking
3. Templating
It has a significant effect on separating the front-end business logic and views and simplifying the data binding process. Without further ado, let’s just look at the example. I won’t talk about how to download it. If you use VS to develop, you can use Nuget to get it done with one click.
1. Basic binding and dependency tracking First you need to define a ViewModel:
From this view you can see the meaning of declarative binding, you only need to use it on the label The data-bind attribute can bind the value of the data to the corresponding place. With View and ViewModel, code is needed to associate the two:
Nothing else needs to be changed. At this time, if you change the value in the input box, when the focus leaves, you can find that the value in p also changes. :
Let’s look at dependency tracking, that is, if a value depends on multiple values, and any one of the values changes, it will automatically change. This is achieved through the computed method, the code is as follows:
Note that getting the value of an observable is a function call. In this way, when the first or last name changes, the fullName will automatically change accordingly.
You can also change the value of the observable through code, and the page will refresh automatically:
After clicking the button, the capitalizeLastName method of the viewmodel will be launched. The way to change the value of an observable is to use the new value as a parameter of the function call. After clicking:
2. List binding
Join us with the following order ViewModel and use observableArray to track changes in the array.
var products=[{name: "Thinkpad X1", price:9000}, {name:"Hp ProBook",price:5555}, {name:"Mouse",price:45} ];
function Order() { var self = this; self.items = ko.observableArray([ //This data should load from server new Item(products[0], 1), new Item(products [1],2)]); self.price = ko.computed(function () { var p=0; for (var i = 0; i < self.items() .length; i ) { var item = self.items()[i]; p = item.product.price * item.amount(); } return p; }, self); }
The Item in Order should actually be obtained from the server. The Item is defined as follows:
< ;button data-bind="click: addMouse">Add a Mouse
At this time, the function of observableArray is reflected. When you click the delete button or the button at the bottom, the page nodes will change accordingly, without the need to manually update the DOM nodes, which greatly simplifies the front-end JS.
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn