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调用加载,有什么区别?感谢
答案 0 :(得分:2)
尝试将param传递给表单控件:
<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