简体   繁体   English

具有绑定的kickout.js

[英]knockout.js with binding

This is probably a really basic question but in the following view model I am populating self.userData from an ajax call. 这可能是一个非常基本的问题,但是在以下视图模型中,我是通过ajax调用填充self.userData的。 I want to display this information in the UI and I figured the 'with' binding is the way to go.. however since self.userData is empty until the ajax function is called I get an error from the with binding 我想在用户界面中显示此信息,我想过要使用“ with”绑定。.但是由于self.userData为空,直到调用了ajax函数,我才从with绑定中获取错误

HTML 的HTML

<div data-bind="with: userData">
    <div data-bind="text: userId"></div>
     ...
</div>

Model 模型

var viewModel = function () {
        var self = this;
        self.userData = {};
        self.login =  function(data) {
            var postData = { ..trimmed out.. };
            $.ajax({
                type: "POST",
                url: "myService",
                data: postData
            }).done(function (data, status) {
                self.userData = ko.mapping.fromJS(data, userData);
                console.log(self.userData);

            }).fail(function (data, status) {
                alert('Could Not Login');
            });
        }

    };
    ko.applyBindings(new viewModel());

Initialize userData with an empty observable, an then set it with the object created by the the mapping plugin once the call return. 用一个空的Observable初始化userData,然后在调用返回后,使用映射插件创建的对象对其进行设置。 Ie change 即改变

self.userData = {};

with

self.userDara = ko.observable();

and change 并改变

self.userData = ko.mapping.fromJS(data, userData);

with

self.userData(ko.mapping.fromJS(data,userData));

You need to initialize userData as an empty observable (single object from ajax call) or observable array (multiple objects) first: 您需要先将userData初始化为空的可观察对象(来自ajax调用的单个对象)或可观察数组(多个对象):

self.userData = ko.observableArray([]);

or 要么

self.userData = ko.observable();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM