Knockoutjs (ko)
Ko's dynamic attributes refer to attributes that are uncertain in ViewModel, but are later required.
What are uncertain attributes? For example, if ListModel edits an item, it wants to change its status to Edit. Data does not include the Edit attribute. An error is reported when mvvm is bound.
So we must expand ko to achieve our goal.
First, we need to know the binding of a value property to a value property:
1. Bind a value property:
JS model:
Copy codeThe Code is as follows:
$ (Function (){
Var viewModel = function (){
Var self = this;
Self. text = ko. observable (1 );
};
Ko. applyBindings (new viewModel ());
});
UI binding:
Copy codeThe Code is as follows:
<Div data-bind = 'text: text'> </div>
Rendering:
Ii. Bind a null Property:
JS model:
Copy codeThe Code is as follows:
$ (Function (){
Var viewModel = function (){
Var self = this;
Self. text = ko. observable ();
};
Ko. applyBindings (new viewModel ());
});
Of course, text is a common value type. Its usage is the same as binding a value property. If it is not a value type and the property is an object, you must use:
UI binding:
Copy codeThe Code is as follows:
<Div data-bind = 'with: text'>
<Div data-bind = "text: property"> </div>
</Div>
3. dynamic attribute binding:
Dynamic attribute binding makes this attribute uncertain. It is difficult to implement it using ko method, so it needs to be expanded.
JS expansion:
Copy codeThe Code is as follows:
// Check the flowers in the fog Q: 397386036
Ko. bindingHandlers. ext = {
Update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ){
Var value = ko. utils. unwrapObservable (valueAccessor ());
For (var handler in value ){
If (value. hasOwnProperty (handler )){
If (typeof viewModel [value [handler] = 'undefined '){
ViewModel [value [handler] = ko. observable ();
}
Ko. bindingHandlers [handler]. update (element, function () {return viewModel [value [handler];});
}
}
}
};
JS model:
Copy codeThe Code is as follows:
$ (Function (){
Var viewModel = function (){
};
Ko. applyBindings (new viewModel ());
});
UI binding:
Copy codeThe Code is as follows:
<Div data-bind = "ext: {text: 'text'}"> </div>
<! -- Event is easy to test -->
<A href = "javascript: void (0)" data-bind = "click: function () {$ data. text (1);} "> change text value </a>
In ext, the first text is the ko text method, and the second text must be a string, which is the attribute of context/viewModel. Therefore, the dynamic attributes of ext can be used in any ko method, such as ext: {text: 'text', value: 'text '}
Rendering: