Knockoutjs abbreviated as ko
Ko’s dynamic attributes refer to attributes that are uncertain in ViewModel but are needed later.
What is an uncertain attribute? For example, if ListModel edits an item, it wants to change the status of this item to Edit. The data does not include the Edit attribute. When mvvm is bound, an error will be reported.
Then we must expand ko to achieve our goal.
First, let’s understand valuable attribute binding and valueless attribute binding:
1. Valuable attribute binding:
JS model:
$(function () {
var viewModel = function () {
var self = this;
self.text = ko.observable(1);
};
ko.applyBindings(new viewModel());
});
UI binding:
Rendering:
2. Valueless attribute binding :
JS Model:
$(function () {
var viewModel = function () {
var self = this;
self.text = ko.observable();
};
ko.applyBindings(new viewModel());
}) ;
Of course text is a general value type, and its usage is the same as that of valuable attribute binding. If it is a non-value type and the attribute is an object, you need to use with:
UI binding:
3. Dynamic property binding:
Dynamic attribute binding, then the attribute itself is uncertain. It is difficult to implement using the ko method, so it needs to be expanded.
JS expansion:
//Looking through the smoke 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:
$(function () {
var viewModel = function () {
};
ko.applyBindings(new viewModel());
});
UI binding:
ext, The first text is the ko text method, and the second text must be a string and is an attribute of context/viewModel. Therefore, the dynamic properties of ext can be used in any ko method, such as ext:{text:'text', value:'text'}
Present: