无法读取未定义的 属性 x / KnockOut

Cannot read property x of undefined / KnockOut

我正在为一个项目学习 KnockOut,我正在尝试绑定输入中的值以将它们推送到 editingUserList。但是,我的绑定功能不起作用。似乎在其中,也无法识别 editingUserList 或其 属性 userKeyValues。 我每次都会收到错误“无法读取未定义的 属性 x”。

$(function () {
  debugger;
  var keyValueModel = function (key, value) {
    var self = this;
    self.key = ko.observable(key);
    self.value = ko.observable(value);
  }

  var ConfidentialUsersListModel = function () {
    var self = this;
    self.userToAdd = ko.observable("");

    self.editingUserList = {
      userKeyValues: ko.observableArray([])
    };

    // (...)
  };

  // binding when a user is selected
  $('#addUser').bind('typeahead:select', function (event, suggestion) {
    var userNameValue = $('#addUser').val();
    // pushing value
    self.editingUserList.userKeyValues.push(new keyValueModel(userNameValue, userNameValue));
    // adding initials of every user
    // setUsersInitials($('.userAddedInitials'), 'userNameShare');
  });
  // apply the model defined above
  ko.applyBindings(new ConfidentialUsersListModel());
})

所以这是视图的一部分:

<form>
  <div class="shareSearchBar">
    <i class="fa fa-search" aria-hidden="true"></i>
    <input id="addUser" class="typeahead" placeholder="Ajouter un utilisateur" data-bind='value: userToAdd, valueUpdate: "keyup"' />
  </div>
  <!-- <select data-bind="options: userNameList" class="dropdown"></select>-->
</form>

(...)

<div class='currentUsers' @*data-bind='visible: editingRoleList.roleKeyValues().length > 0'*@>
    <ul id="confidentialityUsersList" data-bind="template: {name:'userAddedTemplate', foreach: editingUserList.userKeyValues}"></ul>
</div>
<div class="validateSelection">
    <button type="button" class="btn btn-save">@Resources.Validate</button>
    <!--button type="button" class="btn btn-default" data-dismiss="modal">OK</!--button>-->

你有什么想法吗?我可能误解了一些东西并且已经搜索了很多没有运气的例子......谢谢

我以前遇到过同样的问题。如果您显示所有 javascript 代码,我可以更好地评估问题。错误意味着一个对象有一个未定义的变量 x。先检查一下。接下来检查您是否有构造函数。如果你这样做,那么把 一个绑定函数(例如)

    function constructerExample() {
        this.x = something;
        this.functionName = function() {
             this.x;   // Javascript thinks this is refering to the functionName instead of the constructor
        }.bind(this); // this bind function fixes it

您的 jQuery 处理程序在 viewModel 的范围之外,因此 self 未定义。

  var ConfidentialUsersListModel = function () {
    var self = this;
    // ...
    // self goes out of scope at the end of this closure
  };

  $('#addUser').bind('typeahead:select', function (event, suggestion) {
    // self does not exist here
    self.editingUserList.userKeyValues.push(new keyValueModel(userNameValue, userNameValue));
  });

将侦听器提升到 viewModel 中,以便它可以访问 self

  var ConfidentialUsersListModel = function () {
    var self = this;

    $('#addUser').bind('typeahead:select', function (event, suggestion) {
      // self is still in scope
    });

  };

进一步阅读 closures/lexical 范围:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures