【问题标题】:Child view model in KnockoutJS throws exceptions in Internet Explorer 8KnockoutJS 中的子视图模型在 Internet Explorer 8 中引发异常
【发布时间】:2012-01-25 07:00:21
【问题描述】:

我有类似以下内容:

var ChildViewModel = function (viewModel) {
    // state
    this.viewModel = viewModel;
    this.index = ko.dependentObservable(function () {
        return this.viewModel.selections().indexOf(this);
    }, this);
    this.remove = function () {
        this.viewModel.removeSelection(this);
    };
    this.moveUp = function () {
        this.move(-1);
    };
    this.moveDown = function () {
        this.move(1);
    };
    this.move = function (direction) {
        var i = this.index();
        this.remove();
        this.viewModel.selections.splice(i + direction, 0, this);
    };

    // additional properties

};

var viewModel = {
    selections: ko.observableArray(),
    removeSelection: function (item) {
        this.selections.remove(item);
    },
    addSelection: function (event) {
        var child = new ChildViewModel(this);
        this.selections.push(child );
    }
};

ko.applyBindings(viewModel);

当我调用 addSelection 时,我在 KnockoutJS 库中得到了 Object doesn't support this property or method 异常。我的应用程序在 Firefox 3.6 和 Chrome 中运行良好。我在 IE8 中遇到异常。我正在使用 KnockoutJS 的 2.0 版 1.3 Beta

我做错了什么?

【问题讨论】:

  • 您使用的是缩小版的淘汰赛吗?如果是这样,不妨试一试未压缩的版本,看看淘汰赛中的哪一行出错,它可能会为可能的原因提供线索。
  • @AlexKey - 我会更新我的问题。
  • @Daniel:我的错误——我没有意识到 Knockout 有一个 indexOf() 的实现。
  • 也许 'this' 在 addSelection 中没有适当地绑定 - 你是否从元素绑定中调用 addSelection ? (如果是这样,那个绑定是什么样的?)

标签: javascript mvvm knockout.js


【解决方案1】:

好吧,我有 2 个不同的问题。

首先,我去掉了获取数组值的方法,改为使用可观察数组。

 // Bad code for IE8
 this.viewModel.selections().indexOf(this);

 // this works
 this.viewModel.selections.indexOf(this);

另外,我正在设置for 属性。 IE 抱怨 for 是关键字。

// Bad code for IE8
data-bind="attr: { for : logicalOperatorAndFieldId }"

// Good code for IE8
data-bind="attr: { 'for' : logicalOperatorAndFieldId }"

【讨论】:

  • +1,我还遇到了 IE8 声称 class 是关键字的问题:data-bind="attr: { class: InitialClass } 使用字符串解决了它:data-bind="attr: { 'class': InitialClass }
  • 我刚刚在 attr 绑定中遇到了 for 的 IE8 问题。为我节省了大量时间,非常感谢!
【解决方案2】:

不要使用像<span data-bind='text: Text' /> 这样的自闭标签。在IE8、IE7中使用knockout也会导致问题。

【讨论】:

  • 这不能回答我的问题。
猜你喜欢
  • 1970-01-01
  • 2016-01-28
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2013-09-29
  • 2012-09-26
相关资源
最近更新 更多