2014-10-01 60 views
0

我有一些在knockoutjs繼承的proplem。我得到的一個結果淘汰賽和原型不能正常工作

  • 名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沒有觀察到的一切工作正常。 請參閱http://jsfiddle.net/Ly81tbr4/7/

+0

嗯,看來如果刪除與分配原型行,並增加線路** ko.utils.extend(個體經營,新的TreeNode()); **在兩個構造** **根節點和** ComponentNode **一切正常,但我需要做一些測試。 – Sanprof 2014-10-01 19:21:56

回答

2

您不希望將您的觀測值作爲原型的一部分。這樣做會使可觀察的實例在對象的所有實例之間共享。每個實例的可觀測量必須爲

而不是添加observables到原型,只需調用您的子構造函數中的父構造函數。

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

+0

謝謝,傑夫,它確實有效。 – Sanprof 2014-10-01 20:05:34