2015-07-21 34 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/ –

相关问题