Reputation: 2269
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.
Question: Within my HTML, how can I call
FirstName
andLastName
Error States:
Uncaught ReferenceError: Unable to process binding "text: function (){return PersonInfo().FirstName}" Message PersonInfo is not defined
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:
<p data-bind="text: PersonInfo().FirstName"></p>
<p data-bind="text: PersonInfo().LastName"></p>
Upvotes: 1
Views: 191
Reputation: 5085
This line replaces the observable, instead of assigning the value:
modal.PersonInfo = data;
Try this instead:
modal.PersonInfo(data)
There's also a misplaced closing brace: model.setPersonInfo
was inside model.setData
See working demo.
Upvotes: 2
Reputation: 1584
You would need to just use some kind of mapping, for instance 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>
Upvotes: 1