MVVM and ViewModel
Knockout is built on the following three core functions:
- Monitoring properties and Dependency tracking (observables and dependency tracking)
- Declarative binding (declarative bindings)
- Templates (templating)
First let's look at the next MVVM pattern, and the concept of viewmodel.
MVVM (model, view, ViewModel) is a design pattern for creating a user interface that is designed to simply split a complex UI into three parts:
- Model: Used as the storage data in your application;
- View: A visible, interactive UI to show the state of ViewModel;
- ViewModel: Use pure code to show the data and operations of the UI, but any JavaScript object
First create a ViewModel, just declare an arbitrary JavaScript object, for example:
var ViewModel = {name: ' Knockout '};
Then create a declarative binding view for ViewModel, for example:
<div id= "MyView" data-bind= "Text:name" ></div>
Finally activate the knockout, for example
Ko.applybindings (Viewmodel,document.getelementbyid (' MyView '));
The Data-bind property, after all, is not a native HTML attribute, even though it works perfectly, but the browser does not recognize it, you need to activate knockout to make it effective.
This will be a simple viewmodel and view binding together, can display the ViewModel property name in the view, but the view can no longer viewmodel change the time automatically update, ViewModel can no longer view change is automatically updated!
Observables
An important function of the knockout observable (monitoring attribute) is the ability to automatically detect related dependencies and notification subscribers (automatic dependency detection and notification triggering), That is, in establishing a binding relationship between the view and
ViewModel is able to update the value of the other party when one party changes.
We will modify the ViewModel slightly:
var ViewModel = {name:ko.observable ("Knockout")};
Now that he can monitor the changes, the view can be updated automatically.
Read and write operations for monitoring properties:
1. Read the values of the monitoring properties:
Viewmodel.name ();
2. Write a new value into the monitoring attribute:
Viewmodel.name ("new value");
Dependency observables (dependent on monitoring properties)
Define ViewModel:
var ViewModel = {firstName:ko.observable ("first"), lastName:ko.observable ("Last")};
To define dependent monitoring properties:
Viewmodel.fullname = ko.dependentobservable (function () {return this.firstname () + "" + This. LastName ();}, view Model);
Define view:
<div id= "MyView" data-bind= "Text:fullname" ></div>
Depending on the monitoring properties (FirstName, LastName), the Dependency monitor property fullname automatically updates.
"Knockout" second, monitoring properties observables