Knockout.js模板Foreach - 强制完全重新渲染

Ily*_*tok 6 jquery-templates knockout.js

默认情况下,KO"将仅渲染新项目的模板,并将其插入现有DOM".

有没有办法禁用此功能(如,强制KO重新渲染所有项目)?

Ric*_*ard 7

如果您使用jQuery.tmpl的本机{{each koObservableArray()}}语法Knockout无法更新单个项目,但必须重新呈现整个模板

在这里看到更多:http://knockoutjs.com/documentation/template-binding.html

模板引擎的本机"每个"支持:在任何更改之后,模板引擎被迫重新呈现所有内容,因为它不知道KO的依赖性跟踪机制.

如果使用foreach模板模式,则只获得"默认"行为,即:

<div data-bind='template: { name: "personTemplate", 
                            foreach: someObservableArrayOfPeople }'> </div>
Run Code Online (Sandbox Code Playgroud)

  • 如果你想将`{{each}}`与可重用模板一起使用,那么你可以使用`data`参数而不是`foreach`然后`{{each $ data}}来传递你的数组. (3认同)

igm*_*ell 7

我今天遇到了类似的问题,并且能够通过使用自定义绑定替换模板来解决我的团队问题,该自定义绑定首先清除所有ko数据并在渲染之前清空容器.

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

我使用了像这样的无容器模板:

  <ul data-bind="alwaysRerenderForEach: { name: 'itemTmpl', foreach: items }"></ul>
Run Code Online (Sandbox Code Playgroud)

和自定义绑定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);
  }
};
Run Code Online (Sandbox Code Playgroud)

显然有点迟到作为你的查询的答案,但可能会帮助其他人(如我所做的那样).