从Knockout对象访问属性

时间:2016-04-22 21:23:25

标签: javascript jquery knockout.js

以下是该方案:

我目前有一个如下所示的对象:

enter image description here

运行FirstName后,我从第3行开始返回对象。 见上图。

  

问题:在我的HTML中,如何致电LastNameUncaught ReferenceError: Unable to process binding "text: function (){return PersonInfo().FirstName}" Message PersonInfo is not defined

错误状态:

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; } } };

JavaScript的:

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

HTML 我的想法是我可以做到以下几点:

{{1}}

2 个答案:

答案 0 :(得分:2)

此行替换 observable,而不是分配值:

modal.PersonInfo = data;

请改为尝试:

modal.PersonInfo(data)

还有一个错位的右括号:model.setPersonInfo 里面 model.setData

请参阅working demo

答案 1 :(得分:1)

您需要使用某种映射,例如ko.mapping。确保绑定视图模型,以某种方式启动您的功能,您应该没问题。

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>