パフォーマンスが心配な場合は、計算結果で検索結果を反復処理するときにデータを入力する、観測不可能な配列を使用できます。また、ループ内で jQuery を使用して繰り返し選択していることにも注意してください。これにより、KO によるスローダウンが無効になると思います。
self.missedRecords = [];
self.matchedRecords = ko.computed(function() {
var searchQuery = $('.search-input').val().toLowerCase(),
transponders = self.transponders(),
matched = [];
// Clear out missed records
self.missedRecords.length = 0;
_.each(transponders, function(transponder) {
if (transponder.title.toLowerCase().indexOf(searchQuery) >= 0) {
matched.push(transponder);
} else {
self.missedRecords.push(transponder);
}
});
return matched;
});
_.each
コードを短くするためにアンダースコアから使用しました。このアプローチの欠点は、への変更をmissedRecords
(確実に) UI にバインドできないことです (たとえば、foreach
バインディングがある場合)。
配列を監視可能にする必要があり、missedRecords
それでも物事を高速に保ちたい場合は、次のようにすることができます。
self.missedRecords = ko.observableArray([]);
self.matchedRecords = ko.computed(function() {
var searchQuery = $('.search-input').val().toLowerCase(),
transponders = self.transponders(),
matched = [],
missed = [];
_.each(transponders, function(transponder) {
if (transponder.title.toLowerCase().indexOf(searchQuery) >= 0) {
matched.push(transponder);
} else {
missed.push(transponder);
}
});
// Clear out missed records, without triggering subscriptions
self.missedRecords().length = 0;
// Copy the local missed array to the KO observable array
// This will NOT trigger notifications
ko.utils.arrayPushAll(self.missedRecords(), missed);
// Tell KO that the observable array has mutated - this will trigger changes
// to anything observing the missedRecords array
self.missedRecords.valueHasMutated();
return matched;
});
また、完全にスキップcomputed
して変更をサブスクライブするだけで、アレイの状態を変更することもできます。例えば:
self.missedRecords = ko.observableArray([]);
self.matchedRecords = ko.observableArray([]);
self.transponders.subscribe(function(newTransponders) {
var matched = [],
missed = [];
_.each(newTransponders, function(transponder) {
// Populate matched/missed local arrays
});
// Copy the arrays to the observableArray instances using the technique above
});