Does Knockout.js Cleannode Remove All Associated Event Listeners?
I'm loading pages via ajax, on the start of each ajax request I clean the page and then load applybindings on the new page that is added. I keep a persistent model throughout, it's
Solution 1:
First, as you found, you should not use cleanNode
.
Second, you should prefer to have Knockout manage the entire DOM rather than a chunk of it. In your case, you're handling the app the old-fashioned manipulate-the-DOM-yourself way, and managing the changing content with Knockout.
All you really need is a version of the html binding that applies bindings to its content. A simple custom binding handler using applyBindingsToDescendants
can make that work. Example:
ko.bindingHandlers.boundHtml = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
const contentHtml = ko.unwrap(valueAccessor());
element.innerHTML = contentHtml;
ko.applyBindingsToDescendants(bindingContext, element)
}
};
const someContents = [
'First content <span data-bind="text:someValue"></span>',
'Second content <span data-bind="text:anotherValue"></span>',
'Third content <span data-bind="text:someValue() + anotherValue()"></span>'
]
ko.applyBindings({
pageContent: ko.observable('hi there'),
someValue: ko.observable(3),
anotherValue: ko.observable('foo'),
changePage() {
if (someContents.length) {
this.pageContent(someContents.shift());
}
}
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><divdata-bind="boundHtml:pageContent"></div><buttondata-bind="click:changePage">Change</button>
Post a Comment for "Does Knockout.js Cleannode Remove All Associated Event Listeners?"