Knockout.js Foreach Templates - Forcing Reprocessing To End

By default, KO "only displays the template for the new element and inserts it into the existing DOM."

Is there a way to disable this feature (as in, get KO to display all the elements again)?

+6
source share
2 answers

If you use jQuery.tmpl native {{each koObservableArray()}} , the Knockout can not syntax updates individual elements, but must re-get the whole template

see here: http://knockoutjs.com/documentation/template-binding.html

own template engines "each support: after any changes, the template engine is forced to re-display everything because it does not know the KOs dependency tracking mechanism.

You only get the default behavior if you use foreach template mode, i.e.

 <div data-bind='template: { name: "personTemplate", foreach: someObservableArrayOfPeople }'> </div> 
+7
source

Today I faced a similar problem and was able to solve it for my team, replacing the template with a user binding, which first clears all the ko data and frees the container before rendering.

http://jsfiddle.net/igmcdowell/b7XQL/6/

I used a contactless template like this:

  <ul data-bind="alwaysRerenderForEach: { name: 'itemTmpl', foreach: items }"></ul> 

and alwaysRerenderForEach user binding:

 ko.bindingHandlers.alwaysRerenderForEach = { init: function(element, valueAccessor) { return ko.bindingHandlers.template.init(element, valueAccessor); }, update: function(element, valueAccessor, allBindings, viewModel, context) { valueAccessor().foreach(); // touch the observable to register dependency ko.utils.domData.clear(element); // This will cause knockout to "forget" that it knew anything about the items involved in the binding. ko.utils.emptyDomNode(element); //Because knockout has no memory of this element, it won't know to clear out the old stuff. return ko.renderTemplateForEach(valueAccessor().name, valueAccessor().foreach, {}, element, context); } }; 

Obviously, a little late as an answer to your request, but may help others who hit it from the search (like me).

+7
source

Source: https://habr.com/ru/post/897832/


All Articles