Skip to content Skip to sidebar Skip to footer

Knockoutjs Update Child When Parent's Observable Changes

How do I trigger an update to child elements when a parent observable changes using KnockoutJs? In my application, I'm building a translation tool. I have a knockout class that re

Solution 1:

Here is a working example : JsFiddle

functionParentObject(id, defaultValue) {
    varself = this;

    self.id = id;

    self.defaultValue = ko.observable(defaultValue);

    self.defaultValue.subscribe(function(newValue){
        ko.utils.arrayForEach(self.children(), function(child) {
           alert(child.id);
        });
        console.log(newValue);
    });

    self.children = ko.observableArray();

    self.loadChildren = function () {
       // standard code to load the children ("lazy load", as I have gobs of data)
    }
}

functionChild(id, translation, cultureCode) {
    varself = this;

    self.id = id;
    self.cultureCode = cultureCode;
    self.translation= ko.observable(translation);
}


var vm = function() {
    varself = this;
    self.parent = new ParentObject(1,10);
    self.parent.children.push(new Child(1,"A","1A"));
    self.parent.children.push(new Child(2,"B","2B"));
    self.parent.children.push(new Child(3,"C","3C"));
}

var viewModel = new vm();

ko.applyBindings(viewModel);

​ You can use subscribe function to listen observable changes :

self.defaultValue.subscribe(function(newValue){
        ko.utils.arrayForEach(self.children(), function(child) {
           alert(child.id);
        });
        console.log(newValue);
    });

Solution 2:

If you put a reference to parent on child you should be able to do something like..

parent.defaultValue.subscribe(function(newValue){
    //do something on child with newValue
});

The general idea is explained in 'extenders' http://knockoutjs.com/documentation/extenders.html

Post a Comment for "Knockoutjs Update Child When Parent's Observable Changes"