5

我在使用 knockout.js 从子对象获取父对象的特定字段时遇到困难。

function Child(info){
    var self = this;
    self.x = info.x;
    self.y = info.y;
    self.parentThing = parent.fieldToGet();  // This is when I had problem
}

function Main() {
    var self = this;
    self.fieldToGet = ko.observable();
            self.things = ko.observableArray();
    self.postFunction = function(){
        $.post('XXX.php', $("form#filterForm").serialize(), function(data){
                var mappedThing = $.map(data.data, function(info){return new Child(info); });
                self.things(mappedThing);
            }
        }, 'json');
    };
}
var main = new Main();
ko.applyBindings(main, $("div#main")[0]);



层次结构是 Main 有几个 Child。在 Child 对象中,我想获取其父母的“属性”:fieldToGet。

4

1 回答 1

4

我认为一个好的解决方案是将父类作为参数传递给子类

function Child(info, parent){
    var self = this;
    self.parent = parent;
    self.x = info.x;
    self.y = info.y;
    self.parentThing = parent.fieldToGet();  // This is when I had problem
}


function Main() {
    var self = this;
    self.fieldToGet = ko.observable();
    self.things = ko.observableArray();
    self.postFunction = function()
    {
        $.post('XXX.php', $("form#filterForm").serialize(), function(data) {
              var mappedThing = $.map(data.data, function(info) { 
                 return new Child(info, self);        
              });
              self.things(mappedThing);
        }, 'json');
    };
}
  var main = new Main();
  ko.applyBindings(main, $("div#main")[0]);

正如您在我的示例中看到的,父实例 ( self) 将作为参数传递给构造函数 ( function Child(info, parent))中的子类

于 2013-08-13T12:09:34.660 回答