2015-07-21 41 views
0

如何查看在父數據中的子組件

var ParentModel = function() { 
 
    var self = this; 
 
    this.cols = [ 
 
    {name:'id',type:'int'}, 
 
    {name:'name',type:'varchar'}, 
 
    {name:'desc',type:'text'} 
 
    ]; 
 
    this.rows = [ 
 
    {id:1,name:'Peter',desc:'sometext'}, 
 
    {id:2,name:'Jack',desc:'sometext'}, 
 
    {id:3,name:'Mary',desc:'sometext'} 
 
    ]; 
 
    this.current = ko.observable(); 
 
    this.edit = function(e){ 
 
    self.current(e); 
 
    } 
 
} 
 

 
ko.components.register('form-control', { 
 
    
 
    viewModel: function(params) { 
 
     // how i get parent current data from inside component? 
 
    }, 
 
    template: '<input data-bind="value: text" />' 
 
}); 
 
    
 

 
ko.applyBindings(new ParentModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 
<table border="1"> 
 
     <thead> 
 
     <tr> 
 
      <th>#</th> 
 
      <!--ko foreach: cols--> 
 
      <th data-bind="text: name"></th> 
 
      <!--/ko--> 
 
      <th></th> 
 
     </tr> 
 
     </thead> 
 
     <tbody> 
 
     <!--ko foreach: rows--> 
 
     <tr> 
 
      <td data-bind="text: $index"></td> 
 
      <!--ko foreach: $parent.cols--> 
 
      <td data-bind="text:$parent[name]"></td> 
 
      <!--/ko--> 
 
      <td> 
 
       <button data-bind="click: $parent.edit">Edit</button> 
 
      </td> 
 
     </tr> 
 
     <!--/ko--> 
 
     </tbody> 
 
    </table> 
 

 
<span data-bind="text:JSON.stringify(current())"></span> 
 

 
<form> 
 
    <form-control params="data-field: 'id'"></form-control> 
 
</form>

我要呈現的字段/列當前行的數據自動取決於它的數據類型。我該怎麼辦?請告訴我方式。

如果表單內容應該用ajax調用加載,有什麼區別?由於

回答

2

試圖通過參數去形成對照:

<form> 
    <form-control params="data-field: 'id', current: current"></form-control> 
</form> 

而在你的組件使用它:

ko.components.register('form-control', { 

    viewModel: function(params) { 
     this.current = params.current; 
    }, 
    template: '<input data-bind="value: current().name" />' 
}); 

見工作fiddle

+0

有什麼辦法沒有人傳遞參數使用組件?如果我們有這種形式的許多領域。它使我們重複自己。我忘了,謝謝你的回答。 –

+1

您可以將參考傳遞給整個模型'model:$ data'並使用它'viewModel:function(params){return params.model; }' –

+2

另一種選擇是在所有窗體控件組件之間共享父視圖模型的實例,請參閱演示:http://jsfiddle.net/xtoLn37d/1/ –

相關問題