我有一個可觀察的knockout.js:只有當它沒有設置在knockout.js一些值更改觀察到
var test = ko.observable();
test({view: 'abc',model : 'newmodel'});
我要檢查,如果變量test
已經包含:
{view: 'abc',model : 'newmodel'}
如果沒有,我想添加條目。如何在使用knockout.js時檢查此問題?
困難的部分是瞭解對象的細節。
我有一個可觀察的knockout.js:只有當它沒有設置在knockout.js一些值更改觀察到
var test = ko.observable();
test({view: 'abc',model : 'newmodel'});
我要檢查,如果變量test
已經包含:
{view: 'abc',model : 'newmodel'}
如果沒有,我想添加條目。如何在使用knockout.js時檢查此問題?
困難的部分是瞭解對象的細節。
您可以使用()
檢索觀察值的當前值。即:
var currentValue = test();
要檢查是否引用了同一個對象,你可以使用===
操作:
var newValue = { view: 'abc', model: 'newmodel' };
var isTheSame = currentValue === newValue;
注意,當您設置一個可觀察的價值,淘汰賽已經檢查新值實際上不同從舊的一個。如果它們相同,淘汰賽將不會通知任何訂戶(除非您明確告知)。
如果要比較對象是否包含相同的鍵和值,則需要某種「深度比較」方法。 (How to determine equality for two JavaScript objects?)
我不確定「添加條目」是什麼意思。要設置新的對象,使用方法:
test(newValue);
如果你想在newValue
變量test
的價值添加的屬性,你可以使用Object.assign
(make sure to check if your browser supports it)
var combinedValue = Object.assign(currentValue, newValue);
test(combinedValue);
Object.assign
映射所有的其參數的鍵和值到第一個參數對象。它用最新的參數值覆蓋任何重複的鍵。
例如爲:
var test = ko.observable({ a: 1, b: 1 });
var newValue = { b: 2, c: 3 };
test(Object.assign(test(), newValue));
console.log(test()); // Will print: { a: 1, b: 2, c: 3 }
我建議改變你的標題如「*只有在knockout.js *中沒有設置爲某個值時才能改變可觀察性,」因爲這對調試AFAICT沒有任何作用。 – Jeroen