[英]knockout.js computed function to create two arrays?
我有一個對象數組,用戶可以對其執行搜索。 我使用基於搜索的ko.computed函數來創建另一個匹配項數組以供顯示。
self.matchedRecords = ko.computed(function() {
return ko.utils.arrayFilter(self.transponders(), function(r) {
return r.title.toLowerCase().indexOf($('.search-input').val().toLowerCase()) > -1
}
};
這很棒,到目前為止的表現讓我印象深刻。
這個問題是我還需要“不匹配的”記錄,因為在某些情況下(60%的時間)我必須對它們執行加法運算。 我並不是真的想創建第二個ko.computed函數,因為那樣的話,每次執行搜索時,我都必須第二次運行此數組。
所以,我的問題是:有沒有辦法我可以使用相同的ko.computed來創建第二個不匹配項的數組? 基本上遍歷數組並將每個項目放入匹配或不匹配的數組中...
如果不是,是否更快:1)創建第二個ko.compute,以便在用戶搜索時從我的數組中獲取不匹配的項目; 或2)編寫arrayDiff函數,並根據需要確定不匹配的項目。
干杯!
如果您擔心性能,則可以在迭代計算所得的搜索結果時填充一個不可觀察的數組。 還要注意,您在循環中反復選擇使用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
完全跳過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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.