Knockout.js Templates Foreach - force complete re-render

萝らか妹 提交于 2019-11-29 07:15:29

If you use jQuery.tmpl's native {{each koObservableArray()}} syntax Knockout cant update single items but must rerender the entire template

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

the template engine’s native ‘each’ support: after any change, the template engine is forced to re-render everything because it isn’t aware of KO’s dependency tracking mechanism.

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

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

I came across a similar problem today and was able to solve it for my team's issue by replacing the template with a custom binding that first clears all ko data and empties the container before rendering.

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

I used a containerless template like so:

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

and the custom binding alwaysRerenderForEach:

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 query, but may help others who hit this off a search (as I did).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!