如果您擔心性能問題,則可以在迭代計算結果中的搜索結果時填充不可觀察的數組。另外請注意,您在循環中反覆選擇使用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;
});
我使用了Underscore的_.each
來縮短代碼。此方法的缺點是對missedRecords
的更改無法(可靠地)綁定到UI(例如,如果您有綁定foreach
)。
如果您確實需要missedRecords
陣列可觀察到,仍然希望保持快速(ER),你可以做這樣的事情:
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
});
只是用計算出的第二,你都落入過早優化 –