在knockoutjs“未捕获错误:无法解析绑定。”错误,但代码工作

时间:2017-04-18 07:17:06

标签: jquery knockout.js knockout-mapping-plugin

我正在使用knockout js mapping,同时尝试执行示例我遇到了控制台错误。

  

未捕获错误:无法解析绑定。消息:ReferenceError:   loadUserData未定义;绑定值:单击:loadUserData

这里是代码,

<form action="#" method="post">
    <p>First name: <input data-bind='value: firstName' /></p>
    <p>Last name: <input data-bind='value: lastName' /></p>
    <div>
        Your favorite food:
        <select data-bind='options: activities, value: favoriteHobby'></select>
    </div>
    <p><button data-bind='click: loadUserData'>Load data</button></p>
    <p><button data-bind='click: saveUserData'>Save Data</button></p>
</form>
<script>
    function PersonViewModel() {
        var self = this;
        self.firstName = "";
        self.lastName = "";
        self.activities = [];
        self.favoriteHobby = "";
        self.loadUserData = function () {
            $.getJSON("/get-user-data.json", function (data) {
                var viewModel = ko.mapping.fromJS(data);
                ko.applyBindings(viewModel);
            });
        }
        self.saveUserData = function () {
            var data_to_send = { userData: ko.toJSON(self) };
            $.post("/save-user-data", data_to_send, function (data) {
                alert("Your data has been posted to the server!");
            }).fail(function () {
                alert("Ensure the Url before save the data");
            });
        }
    }
    ko.applyBindings(new PersonViewModel());
</script>

获取用户-data.json

{
   "firstName": "John",
   "lastName": "Smith",
   "activities": [ "Golf", "Kayaking", "Web Development" ],
   "favoriteHobby": "Golf"
}

点击加载数据按钮时出现错误,但示例有效,如何清除此错误。

1 个答案:

答案 0 :(得分:1)

正如@ user3297291指出的那样,你不能两次调用ko.applyBindings。相反,使视图模型敲除observables和knockout的属性会在更改时自动更新UI:

function PersonViewModel() {
    var self = this;
    self.firstName = ko.observable();
    self.lastName = ko.observable();
    self.activities = ko.observableArray();
    self.favoriteHobby = ko.observable();
    self.loadUserData = function () {
        return $.getJSON("/get-user-data.json", function (result) {
            self.firstName(result.firstName)
                .lastName(result.lastName)
                .favoriteHobby(result.favoriteHobby)
                .activites(result.activities);
        });
    }
}
ko.applyBindings(new PersonViewModel());