0

我正在渲染一个接受可观察数组的模板,在内部,它使用内部模板将属性的内容呈现为输入文本。如果我直接在父级的“foreach”中渲染输入文本,那么对文本的任何更改都是双向绑定并反映在相关的可观察数组项属性中,但是当使用内部模板时,它变成了一种方式。

--========== 父模板 =======--

  <div class="skill-rating-section" data-bind="foreach: { data: skills, as: 'skill' }">
        <div class="col-comment">

            **<!-- This works fine - two way bdinding -->**
            <input type="text" data-bind="value:skill.Comment" />

            **<!-- This renders the content but is not two way binding -->**
            <skill-rating-comment params="viewModel:skill"></skill-rating-comment>
        </div>
    </div>

--===== 用于内部模板的 Html(SkilRatingCommentTemplate.html)====

<input type="text" data-bind="value:comment" />

--======= 内部模板的js代码================

define('SkillRating/Component/SkilRatingCommentComponent', ['knockout'], function (ko) {
    function skillRatingCommentViewModel(params) {
        var me = this;     
        me.comment = params.viewModel.Comment;
        return me;
    }
    ko.components.register('skill-rating-comment', {
        viewModel: skillRatingCommentViewModel,
        template: {
            require: 'text!../../Content/HtmlTemplate/SkillAssessmentComponent/SkilRatingCommentTemplate.html'
        }
    });
});
4

1 回答 1

1

这实际上似乎有效。看看下面的片段。我稍微更新了 HTML 以强调外部和内部(组件)绑定,并将 value 绑定更改为 textInput 绑定以立即查看相关 observable 中的更改。

function skillRatingCommentViewModel(params) {
  var me = this;
  me.comment = params.viewModel.Comment;
  return me;
}

ko.components.register('skill-rating-comment', {
  viewModel: skillRatingCommentViewModel,
  template: '<p>Inner <input type="text" data-bind="textInput:comment" /></p>'
});

ko.applyBindings({
  skills: ko.observableArray([{
    Comment: ko.observable('Comment 1')
  }, {
    Comment: ko.observable('Comment 2')
  }])
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="skill-rating-section" data-bind="foreach: { data: skills, as: 'skill' }">
  <div class="col-comment">
    <p>Outer <input type="text" data-bind="textInput:skill.Comment" /></p>
    <skill-rating-comment params="viewModel:skill"></skill-rating-comment>
  </div>
  <hr/>
</div>

于 2020-10-29T07:15:30.827 回答