淘汰赛订阅可观察的复杂对象的任何更改 [英] Knockout Subscribe to any change in observable complex object

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

问题描述

我有一个视图模型,其中包含一个可观察对象,该对象是用对象初始化的. 该对象本身包含可观察对象.

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解决方案(在评论中链接).复杂对象上的脏标志的问题是,当它切换为"true"并且我迷上了该标志的订阅时,那第一次就可以了.为了对进一步的变化做出反应,我需要再次将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.

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

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