2

次のような KnockoutJS テンプレートがあります。

<div data-bind="template: {name: 'testTemplate', data: people}"></div>

<script id="testTemplate" type="text/html">
    <!--ko foreach: $data-->        
    <div class="items" data-bind="text: full() + ' updated at: ' + Date()"></div>
    <!--/ko-->
</script>

N 回目のテストを実行した後、データが変更されていなくても、KnockoutJS は毎回テンプレートを更新するため、このようなテンプレートの作成には欠陥があることに気付きました。

これらの 2 つのフィドルを使用してこれを説明しました。

ご覧のとおり、最初の読み込みをパウンドするか、foreach バインディングで更新されたデータ ボタンを読み込むと、データが実際に変更されない限り、UI は再レンダリングされません。残念ながら、データ スタイル バインディングで同じことを行うと、毎回再レンダリングされます。

私は本当に違いが何であるかを理解できません。データ バインディングは foreach と同じように機能するが、テンプレート内のオブジェクトをより細かく制御できるという印象を受けました。

私がこれを使用している唯一の理由は、ネストされたテンプレートのセットがあり、手元にある実際のオブジェクトに近づく必要があるからです。私はリファクタリングしてそのアプローチから逃れることができるはずですが、なぜそれが問題なのか疑問に思っています。

<!--ko foreach:-->foreach テンプレート バインディングが使用するのと同じパターンを尊重すべきではありませんか?

4

1 に答える 1

3

The issue is that your template binding creates a subscription to your people observableArray as it is passed as the data. When the people array is updated (items pushed/removed, etc.), then this will trigger the template binding to re-render the template. In your case, this re-renders all of the content, so the foreach inside of the template never gets a chance to be efficient.

An easy way to avoid this is to make sure that the template binding does not unwrap your people observableArray. You can pass the data like { myArray: people } and then do your foreach on myArray.

Here is a sample: http://jsfiddle.net/rniemeyer/bVPwM/4/

于 2012-04-13T22:04:53.853 に答える