KnockOut无法解析绑定。引发ReferenceError

时间:2013-11-04 13:01:55

标签: javascript knockout.js

错误:无法解析绑定。消息:ReferenceError:未定义消息;绑定值:text:message。

我无法弄清楚绑定失败的原因。

以下是javascript代码:

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

        function LogItem($root, appName, level, message) {
            self.appName = ko.observable(appName);
            self.level = ko.observable(level);
            self.message = ko.observable(message);
        }

        self.logItems = ko.observableArray();

        self.add = function (appName, level, message) {
            self.logItems.push(new LogItem(self, appName, level, message));
        };
    };


    $(document).ready(function () {
        var logItemModel = new LogItemModel();
        ko.applyBindings(logItemModel);
        var url = "http://localhost:49091/api/Log";

        $.getJSON(url, function (result) {
            $.each(result, function (idx, logItem) {
                logItemModel.add(logItem.ApplicationName, logItem.Level, logItem.Message);
                debugger;
            });
        }).error(function (e) {
        });

    });

以下是html代码:

<div id="LogItemList" data-bind="foreach:logItems">
    <span data-bind="text: message"></span>
</div>

我甚至尝试将绑定应用于LogItemList元素

ko.applyBindings(logItemModel,$(“#LogItemList”)[0]);

但即使这样也行不通。

1 个答案:

答案 0 :(得分:2)

function LogItem($root, appName, level, message) {
    self.appName = ko.observable(appName);
    self.level = ko.observable(level);
    self.message = ko.observable(message);
}

在此函数中,在LogItemModel中引用self,将其更改为:

function LogItem($root, appName, level, message) {
    var that = this;
    that.appName = ko.observable(appName);
    that.level = ko.observable(level);
    that.message = ko.observable(message);
}