Knockout.js 2.2.1找不到可观察的数组

时间:2013-02-19 00:08:52

标签: javascript mvvm knockout.js knockout-2.0

不确定这里出了什么问题,但KnockoutJS在查找我的MasterViewModel内的可观察数组时遇到了一些问题。将2.2.1与jQuery 1.8.x一起使用,而不是我的第一个KJS应用。这是:

初始化

$(function() {
  window.vm = new MasterViewModel();
  ko.applyBindings(vm);
});

视图模型

function MasterViewModel(data) {
  var self = this;
  self.currentAppView = ko.observable();

  // Users
  self.userList = ko.observableArray([]);
  self.templateListGetter = ko.computed(function() {
    $.getJSON("/user/list"), function(data) {
      var mapped = $.map(data, function(item) { return new userModel(item) });
      self.userList(mapped);
    };
  });

  self.goToAppView = function(appView) { 
    location.hash = '!/' + appView;
  };    
  Sammy(function() {
      this.get('#!/:appView', function() {
        self.currentAppView(this.params.appView);
        $('.appview').hide();
        ko.applyBindings(new window[this.params.appView+'VM']());
      });
      this.notFound = function(){
        location.hash = "!/dashboard";
      }
      //this.raise_errors = true;
  }).run();
}

视图

  <table class="table table-bordered table-striped">
    <tbody data-bind="foreach: userList">
      <tr>
        <td data-bind="text: guid"></td>
        <td data-bind="text: firstName"></td>
        <td data-bind="text: lastName"></td>
        <td data-bind="text: email"></td>
        <td data-bind="text: updated"></td>
        <td data-bind="text: suspended"></td>
      </tr>
    </tbody>
  </table> 

我正在加载一个简单的表

即使仔细检查了一些事情,例如将defer="defer"添加到我的JS代码并确保userList存在,它也无法找到observableArray。它给出了错误:

Message: ReferenceError: userList is not defined;
Bindings value: foreach: userList Error {} 

任何人都知道发生了什么事?

更新

对于那些想知道每次哈希值改变时调用的内容的人:

function usersVM() {
    // Data
    var self = this;
    // Behaviours
    $('#users').show();
}

1 个答案:

答案 0 :(得分:1)

看起来你是用未定义的视图模型初始化淘汰赛?

ko.applyBindings(new window[this.params.appView+'VM']());,但您的实际视图模型为window.vm。区分大小写。此外,窗口上的视图模型已经创建/初始化。因此,您不需要new运算符。

因此,将applyBindings行更改为

ko.applyBindings(window[this.params.appView+'vm']());

更新的答案:海报

每次路由更改时都没有必要继续运行ko.applyBindings,因为它已经在页面加载时应用了绑定。所以Sammy.js改为:

  Sammy(function() {
      this.get('#!/:appView', function() {
        self.currentAppView(this.params.appView);
        $('.appview').hide();
        window[this.params.appView+'Route']();
      });
      this.notFound = function(){
        location.hash = "!/dashboard";
      }
      //this.raise_errors = true;
  }).run();

它看起来像ko.computed,或者对window.vm.getUserList()的常规函数​​调用运行不正常,但这将保存为另一个问题。

function usersRoute() {
    // Data
    var self = this;
    // Behaviours
    $('#users').show();
    window.vm.getUserList();
}