Brief introduction
This article mainly to the source code and internal mechanism to do a deeper analysis, the basic part please refer to the official website documentation.
Knockout.js ( ko ) is one of the first important contributors to introducing MVVM to the front end. The current version has been updated to 3. Compared with the main characteristics of the same:
Duplex binding is based on observe mode and has high performance.
The plug-ins and extension mechanisms are perfect, both in the data layer and the presentation layer to meet a variety of complex requirements.
Down support to IE6
Documentation, testing is complete, community is more active.
Entrance
The following analysis will be compared to the 3.x version on GitHub. One thing needs to know first: Ko uses google closure compiler for compression because closure compiler will change the code itself in a certain way when compressing, so there are many similar ko.exportsymbol in Ko Source ( ' Subscribable ', Ko.subscribable's statement to prevent references from being lost while compressing. Readers who are willing to get to know each other can read closure compiler first, and can skip it without understanding it.
Startup code Example:
var App = function () {
this.firstname = ko.observable (' Planet ');
This.lastname = ko.observable (' earth ');
This.fullname = ko.computed ({
read:function () {return
this.firstname () + "" + this.lastname ();
},
WRI Te:function (value) {
var lastspacepos = Value.lastindexof ("");
if (Lastspacepos > 0) {
this.firstname (value.substring (0, Lastspacepos));
This.lastname (value.substring (Lastspacepos + 1));
}
,
owner:this
});
Ko.applybindings (New App,document.getelementbyid (' ID '))
Turn directly to the source/src/subscribables/observable.js the first line.
ko.observable = function (initialvalue) {var _latestvalue = InitialValue; function observable () {if (Arguments.length > 0) {//Write//Ignore writes if the VA Lue hasn ' t changed if (Observable.isdifferent (_latestvalue, arguments[0])) {OBSERVABLE.VALUEW
Illmutate ();
_latestvalue = Arguments[0];
if (DEBUG) observable._latestvalue = _latestvalue;
Observable.valuehasmutated (); return to this; Permits chained assignments} else {//Read KO.DEPENDENCYDETECTION.REGISTERDEP Endency (observable);
The caller only needs to is notified of changes if they did a "read" Operation return _latestvalue;
} ko.subscribable.call (observable);
Ko.utils.setPrototypeOfOrExtend (observable, ko.observable[' FN ']);
if (DEBUG) observable._latestvalue = _latestvalue; /**Here omitted the special for closure compiler writes the statement **/<br> return observable; }