KnoutJS cleanup templating.js a bit

This commit is contained in:
the-djmaze 2024-03-03 16:46:54 +01:00
parent 97a369048e
commit 0f0f60e456

View file

@ -112,9 +112,9 @@
} else {
console.log('no targetNodeOrNodeArray');
}
};
},
ko.renderTemplateForEach = (template, arrayOrObservableArray, options, targetNode, parentBindingContext) => {
renderTemplateForEach = (template, arrayOrObservableArray, options, targetNode, parentBindingContext) => {
// Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
// activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
var arrayItemContext;
@ -139,7 +139,7 @@
arrayItemContext = null;
};
var setDomNodeChildrenFromArrayMapping = function (newArray, changeList) {
var setDomNodeChildrenFromArrayMapping = (newArray, changeList) => {
// Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
// If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, newArray, executeTemplateForArrayItem, options, activateBindingsCallback, changeList]);
@ -158,22 +158,23 @@
}
return ko.computed(() => {
var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
if (!Array.isArray(unwrappedArray)) // Coerce single value into array
unwrappedArray = [unwrappedArray];
setDomNodeChildrenFromArrayMapping(unwrappedArray);
}, { disposeWhenNodeIsRemoved: targetNode });
};
},
var templateComputedDomDataKey = ko.utils.domData.nextKey();
function disposeOldComputedAndStoreNewOne(element, newComputed) {
templateComputedDomDataKey = ko.utils.domData.nextKey(),
disposeOldComputedAndStoreNewOne = (element, newComputed) => {
var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
oldComputed?.['dispose']?.();
ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && (!newComputed.isActive || newComputed.isActive())) ? newComputed : undefined);
}
},
cleanContainerDomDataKey = ko.utils.domData.nextKey();
var cleanContainerDomDataKey = ko.utils.domData.nextKey();
ko.bindingHandlers['template'] = {
'init': (element, valueAccessor) => {
// Support anonymous templates
@ -239,8 +240,7 @@
if ('foreach' in options) {
// Render once for each data point (treating data set as empty if shouldDisplay==false)
var dataArray = (shouldDisplay && options['foreach']) || [];
templateComputed = ko.renderTemplateForEach(template, dataArray, options, element, bindingContext);
templateComputed = renderTemplateForEach(template, (shouldDisplay && options['foreach']) || [], options, element, bindingContext);
} else if (!shouldDisplay) {
ko.virtualElements.emptyNode(element);
} else {