Knockout.js Make every nested object an Observable

后端 未结 6 1738
轻奢々
轻奢々 2020-12-04 22:00

I am using Knockout.js as a MVVM library to bind my data to some pages. I\'m currently building a library to make REST calls to a web service. My RESTful web service returns

6条回答
  •  时光说笑
    2020-12-04 22:16

    I don't think knockout has a built-in way to observe changes to child elements. If I understand your question, when someone changes the name you want a change to details as an entity to be noticed. Can you give a concrete example of how you would use this? Would you use a subscription to the details observable to perform some action?

    The reason your code doesn't make details an observable is because javascript is pass by value, so changing the value of the 'object' argument in your function doesn't change the actual value you passed, only the value of the argument inside your function.

    Edit

    If changes will automatically propagate to the parents, this should make all children observable I think, but your root that you pass the first time should already be an observable.

    // object should already be observable
    var makeChildrenObservables = function (object) {
        if(!ko.isObservable(object)) return;
    
        // Loop through its children
        for (var child in object()) {
            if (!ko.isObservable(object()[child])) {
                object()[child] = ko.observable(object()[child]);
            }
            makeChildrenObservables(object()[child]);
        }
    };
    

提交回复
热议问题