检测对 Knockout 视图模型的更改 [英] Detecting change to Knockout view model
本文介绍了检测对 Knockout 视图模型的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当然这是一个很容易回答的问题,但有没有一种简单的方法来确定淘汰赛视图模型的任何属性是否发生了变化?
Sure this is a very easy question to answer but is there an easy way to determine if any property of a knockout view model has changed?
推荐答案
使用扩展器:
ko.extenders.trackChange = function (target, track) {
if (track) {
target.isDirty = ko.observable(false);
target.originalValue = target();
target.setOriginalValue = function(startingValue) {
target.originalValue = startingValue;
};
target.subscribe(function (newValue) {
// use != not !== so numbers will equate naturally
target.isDirty(newValue != target.originalValue);
});
}
return target;
};
那么:
self.MyProperty= ko.observable("Property Value").extend({ trackChange: true });
现在你可以像这样检查:
Now you can inspect like this:
self.MyProperty.isDirty()
您还可以编写一些通用的 viewModel 遍历以查看是否有任何更改:
You can also write some generic viewModel traversing to see if anything's changed:
self.isDirty = ko.computed(function () {
for (key in self) {
if (self.hasOwnProperty(key) && ko.isObservable(self[key]) && typeof self[key].isDirty === 'function' && self[key].isDirty()) {
return true;
}
}
});
... 然后在 viewModel 级别检查
... and then just check at the viewModel level
self.isDirty()
这篇关于检测对 Knockout 视图模型的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文