我在基因敲除js中有一些继承问题。我得到下一个结果


  
  名称1(ID1)
  
  name6(id6)
  name6(id6)
  name6(id6)
  
  name6(id6)
  name6(id6)
  
  
  


<ul>
    <li data-bind="text: name() + ' (' + id() + ')'"></li>
    <ul data-bind="template: { name: 'nodeTree', foreach: nodes }">
    </ul>
</ul>
<script type="text/html" id="nodeTree">
    <li data-bind="text: name() + ' (' + id() + ')'"></li>
    <ul data-bind="template: { name: 'nodeTree', foreach: nodes }">
    </ul>
</script>
<script>
    var TreeNode = function () {
        var self = this;
        self.id = ko.observable();
        self.name = ko.observable();
        self.nodes = ko.observableArray();
    }

    var RootNode = function () {
        var self = this;
        self.id(dataModel.id);
        self.name(dataModel.name);
        self.nodes = ko.computed(function () {
            return DataToArray(dataModel.component);
        });
    }

    var ComponentNode = function (data) {
        var self = this;
        var that = new TreeNode();
        if (data !== null) {
            that.id(data.id);
            that.name(data.name);
            if (data.component && data.component.length > 0)
                that.nodes = DataToArray(data.component);
        }
    }
    ComponentNode.prototype = new TreeNode();
    RootNode.prototype = new TreeNode();

    function DataToArray(mass) {
        var arr = [];
        if (mass !== null) for (var i = 0; i < mass.length; i++) {
            var obj = new ComponentNode(mass[i]);
            arr.push(obj);
        }
        return arr;
    }

    var dataModel = {
        id: "id1",
        name: "name1",
        component: [{
            id: "id2",
            name: "name2",
            component: []
        }, {
            id: "id3",
            name: "name3",
            component: []
        }, {
            id: "id4",
            name: "name4",
            component: [{
                id: "id5",
                name: "name5",
                component: []
            }, {
                id: "id6",
                name: "name6",
                component: []
            }]
        }]
    };

    ko.applyBindings(new RootNode());
</script>


我不明白为什么当无法观察到属性id和name时,它们都能正常工作。
http://jsfiddle.net/Ly81tbr4/7/

最佳答案

您不想将可观测对象作为原型的一部分。这样做使可观察实例在对象的所有实例之间共享。每个实例的可观察值必须唯一。

与其在原型中添加可观察对象,不如在子构造函数中调用父构造函数。

var TreeNode = function () {
    this.id = ko.observable();
    this.name = ko.observable();
    this.nodes = ko.observableArray();
}

var RootNode = function (model) {
    TreeNode.call(this);
    ...
}
var ComponentNode = function (data) {
    TreeNode.call(this);
    ...
}


fiddle

09-25 18:39