简体   繁体   English

从Knockout对象访问属性

[英]Access Properties from Knockout Object

Here is the scenario: 这是场景:

I currently have an object that looks like the following: 我目前有一个如下所示的对象:

在此输入图像描述

After running modal.PersonInfo I get the object returned starting at line 3. See image above. 运行modal.PersonInfo我从第3行开始返回返回的对象 见上图。

Question: Within my HTML, how can I call FirstName and LastName 问题:在我的HTML中,如何调用FirstNameLastName

Error States: 错误状态:

Uncaught ReferenceError: Unable to process binding "text: function (){return PersonInfo().FirstName}" Message PersonInfo is not defined

JavaScript: JavaScript的:

function Person() {
    var modal = this;
    modal.PersonInfo = ko.observable('');

    modal.setData = function (id) {
        $.ajax({
            type: "GET",
            url: '/Person/UserInformation?id=' + id,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                modal.setPersonInfo(data);

                $('#person-modal').modal('show');
            }
        });

        modal.setPersonInfo = function (data) {
            modal.PersonInfo = data;
        }
    }
};

HTML My thought was that I could do the following: HTML我的想法是我可以做以下事情:

<p data-bind="text: PersonInfo().FirstName"></p>
<p data-bind="text: PersonInfo().LastName"></p>

This line replaces the observable, instead of assigning the value: 此行替换了observable,而不是赋值:

modal.PersonInfo = data;

Try this instead: 试试这个:

modal.PersonInfo(data)

There's also a misplaced closing brace: model.setPersonInfo was inside model.setData 还有一个错位的model.setPersonInfo括号: model.setPersonInfo model.setData

See working demo . 工作演示

You would need to just use some kind of mapping, for instance ko.mapping. 您需要使用某种映射,例如ko.mapping。 Make sure you bind your view model, start your function in some way and you should be ok. 确保绑定视图模型,以某种方式启动您的功能,您应该没问题。

 var DemoPage = (function () { function DemoPage() { var _this = this; _this.PersonInfo = ko.observable({}); _this.setData = function (id) { // some ajax that returns data var _data = { FirstName: 'Frankie', LastName: 'Jones' }; _this.setPersonInfo(_data); //$('#person-modal').modal('show'); }; _this.setPersonInfo = function (data) { ko.mapping.fromJS(data, {}, _this.PersonInfo()); }; this.setData(); } return DemoPage; })(); var demoApp = new DemoPage(); ko.applyBindings(demoApp); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script> <p data-bind="text: PersonInfo().FirstName"></p> <p data-bind="text: PersonInfo().LastName"></p> 

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

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