【问题标题】:How to acces to parent data in child component如何访问子组件中的父数据
【发布时间】:2015-07-21 04:51:38
【问题描述】:

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 调用加载,有什么区别?谢谢

【问题讨论】:

    标签: knockout.js components viewmodel


    【解决方案1】:

    尝试将参数传递给表单控件:

    <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

    【讨论】:

    • 在使用组件时有没有什么办法让没人传参数?如果我们在这种形式中有很多字段。它使我们重复自己。我忘了,谢谢你的回答。
    • 您可以将引用传递给整个模型model: $data 并使用它viewModel: function(params) { return params.model; }
    • 另一种选择是在所有表单控制组件之间共享父视图模型的实例,请参阅演示:jsfiddle.net/xtoLn37d/1
    • 我在使用 requirejs 按需加载组件时遇到问题。使用上面的表单控制。我想调用 Ajax 来获取动态模板,但是 Ajax 调用是异步的,并且返回的组件对象没有模板。如何使其正常工作? knockoutjs.com/documentation/component-registration.html
    • 所以.. 这不是一个很好的答案。如果在我的组件标记中,我使用了with 绑定或foreach,我如何弹出来引用组件级别的内容?
    猜你喜欢
    • 2020-04-14
    • 2023-01-12
    • 2017-03-17
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    相关资源
    最近更新 更多