首页 文章

Knockoutjs在父级的可观察变化时更新子级

提问于
浏览
3

当父observable使用KnockoutJs更改时,如何触发对子元素的更新?

在我的应用程序中,我正在构建一个翻译工具 . 我有一个淘汰类,它代表一些文本的原始(默认)值,带有一个已翻译的子集合:

function ParentObject(id, defaultValue) {
    var self = this;

    self.id = id;
    self.defaultValue = ko.observable(defaultValue);

    self.children = ko.observableArray();

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

孩子是

function Child(id, translation, cultureCode) {
    var self = this;

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

父项的defaultValue属性绑定到输入控件 .

我想要做的是在更新父项的默认值时为每个孩子调用我的翻译服务 . 但我对如何继续有点迷茫 .

  • 如何识别父母的"defaultValue"属性已更改?

  • 当发生这种情况时,我是否应该迭代父母中的孩子,或者以某种方式将其移动到孩子身上?

(注意,我的例子从实际实现中简化)

EDIT: 将此函数与函数一起添加到我的defaultValue元素中,仍然传递旧值:

data-bind=" value: defaultValue, event: {change: updateChildren}"

其中updateChildren迭代子数组 .

2 回答

  • 2

    这是一个工作示例:JsFiddle

    function ParentObject(id, defaultValue) {
        var self = 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)
        }
    }
    
    function Child(id, translation, cultureCode) {
        var self = this;
    
        self.id = id;
        self.cultureCode = cultureCode;
        self.translation= ko.observable(translation);
    }
    
    
    var vm = function() {
        var self = 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);
    

    您可以使用subscribe函数来监听可观察的更改:

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

    如果您在孩子身上提到父母的参考,您应该可以做类似的事情 .

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

    一般的想法在'extenders' http://knockoutjs.com/documentation/extenders.html中解释

相关问题