检测Knockout视图模型的更改 [英] Detecting change to Knockout view model

查看:91
本文介绍了检测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 });

现在您可以这样检查:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆