Knockout 订阅可观察的复杂对象的任何变化 [英] Knockout Subscribe to any change in observable complex object

查看:22
本文介绍了Knockout 订阅可观察的复杂对象的任何变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个 observable 的 viewmodel,它用一个对象初始化.此对象本身包含可观察对象.

I have a viewmodel which contains an observable, which is initialized with an object. this object itself contains observables.

我的目标是在该对象发生变化时(或:当该对象中的任何可观察对象发生变化时)收到通知

my goal is to be notified whenever that object changes (or: when any observable in that object changes)

jsfiddle

复杂对象:

var ns = ns || {};

ns.ComplexObj = function (item) {
    var self = this;

    if (!item) {
        item = {};
    }

    self.id = item.Id || '';
    self.company = ko.observable(item.Company || '');
    self.email = ko.observable(item.Email || '');

    self.company.subscribe(function () {
       console.log('debug: company changed');
    });

    return self;
};

视图模型

ns.mainvm = function () {
   var simpleObject = ko.observable('i am pretty simple');

   simpleObject.subscribe(function (newValue) {
       document.getElementById('simpleSubscribtionFeedback').innerText = newValue;
   });

   var complexObject = ko.observable(ns.ComplexObj());
   complexObject.subscribe(function (newValue) {
       // i would like to react to any change in complex object
       document.getElementById('complexSubscribtionFeedback').innerText = 'i dont get executed :(';
   });

   return {
       simpleObject: simpleObject,
       complexObject: complexObject
   };
};

绑定

var container = document.getElementById('wrapper');
if (container) {
   ko.applyBindings(ns.mainvm, container);
} else {
   console.warn("container for binding ko not found");
}

是否有可能对复杂对象的变化做出反应?任何帮助表示赞赏.

is there any possiblity to react on changes on a complex object? any help is appreciated.

我已经尝试过来自 rpniemeyer 的dirtyFlag 解决方案(链接在评论中).复杂对象上的脏标志的问题是,当它切换到真"并且我正在连接该标志的订阅时,这只是第一次.为了对进一步的变化做出反应,我需要再次将dirtyFlag设置为false(在订阅中完成我的工作之后).这将导致订阅循环.

i already tried the dirtyFlag solutions (link in the comments), from rpniemeyer. the problem with a dirty flag on the complex object is, that when it switches to "true" and i'm hooking into the subscription of that flag, thats only ok for the first time. to react to further changes, i would need to set the dirtyFlag to false again (after doing my stuff in the subscription). which would lead into a subscription loop.

推荐答案

您可以使用以下技巧:

ko.computed(function() {
    return ko.toJSON(complexObject);
}).subscribe(function() {
    // called whenever any of the properties of complexObject changes
});

http://jsfiddle.net/xcajt4qn/3/

这样做的原因是 ko.toJSON 将递归读取对象中的所有属性,因此使计算依赖于所有属性.

The reason why this works is ko.toJSON will recursively read all the properties in the object, therefore making the computed depend on all the properties.

这篇关于Knockout 订阅可观察的复杂对象的任何变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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