未捕获的ReferenceError:无法处理与KnokoutJS的绑定

2022-04-07 00:00:00 javascript knockout.js razor viewmodel
我们有一个如下所示的多页表单,表单上的每个页面都与不同的模型类相关联。我正在尝试使用用户在第1页中选择的值,并且根据在第1页中选择的值,我需要在第2页中显示/隐藏该字段。

Page2有一个按钮,允许用户添加课程,当他们点击foreach循环中的按钮时,页面中显示的字段很少,其中一个字段应该根据前一页上的选择显示/隐藏。但上面的逻辑抛出的错误与Uncaught ReferenceError: Unable to process binding "visible:"类似,下面是viewmodel

如何才能使绑定在此处正常工作并消除错误


解决方案

只要用一个非常基本的可运行示例来扩展@Woodrow兄弟的答案,可能会对事情有所帮助。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
function ViewModel() {
  var self = this;
  self.pages = [1, 2]
  self.currentPage = ko.observable(1)
  self.solutions = ko.observableArray(['Solution 1', 'Solutions 2', 'Other']);
  self.solution = ko.observable().extend({
    required: {
      params: true,
      message: "Required"
    }
  });
  self.next = function() {
    self.currentPage(self.currentPage() + 1);
  };
  self.back = function() {
    self.currentPage(self.currentPage() - 1);
  };
  self.CourseDetails = ko.observableArray();

  self.addCourse = function() {
    self.CourseDetails.push(new coursesList());
  }
  self.pageVisible = function(page) {
    return self.currentPage() == page;
  }
}

function coursesList() {
  var self = this;
  self.otherSolution = ko.observable().extend({
    required: {
      params: true,
      message: "Required"
    }
  });

}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="Page_1" data-bind="visible: pageVisible(1)">
  <h2>Page 1</h2>
  <div class="form-group required">
    <label for="Solution" class="control-label">Solution</label>
    <select id="Solution" name="Solution" class="form-control" data-bind="options: solutions, value: solution, optionsCaption: 'Select'"></select>
  </div>

  <button type="submit" id="NtPg" class="SubmitButton" data-bind="click: next">Next</button>
</div>

<div id="Page_2" data-bind="visible: pageVisible(2)">
  <h2>Page 2</h2>
  <button type="submit" id="AddCourseInfo" class="SubmitButton" data-bind="click: addCourse">Add Course Info</button>
  <div data-bind="foreach:CourseDetails">
    <div class="form-group required" data-bind="visible: $parent.solution() == 'Other'">
      <label for="OtherSolution" class="control-label">Explain Other Solution : </label>
      <input type="text" maxlength="1000" id="OtherSolution" name="OtherSolution" class="form-control" data-bind="value : otherSolution" required/>
    </div>
  </div>
  <button type="submit" id="NtPg" class="SubmitButton" data-bind="click: back">Back</button>
</div>

<pre data-bind="text: ko.toJSON($root)"></pre>

相关文章