Knockout.js Templates Foreach - force complete re-render

前端 未结 2 661
一生所求
一生所求 2020-12-18 04:38

By default, KO \"will only render the template for the new item and will insert it into the existing DOM\".

Is there a way to disable this feature (as in, force KO t

2条回答
  •  没有蜡笔的小新
    2020-12-18 05:18

    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:

      

      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).

    提交回复
    热议问题