淘汰赛和原型不能正常工作

时间:2014-10-01 18:37:37

标签: javascript knockout.js

我在knockoutjs中有一些继承的问题。我得到了下一个结果

  
      
  • name1(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/

1 个答案:

答案 0 :(得分:2)

您不希望将您的可观察量作为原型的一部分。这样做可以在对象的所有实例之间共享可观察的实例。每个实例的observable 必须唯一。

不是将observable添加到原型中,只需在子构造函数中调用父构造函数。

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