I am new to knockout and I am having a problem with using the mapping plugin as I do not understand how it maps my JSON data.
This is a sample json data similar to what is in my program:
contact: {
name : 'John',
email : '[email protected]',
phones : [{
phoneType : 'Home Phone',
phoneNumber: '999-888-777'},
{
phoneType : 'Business Phone',
phoneNumber: '444-888-777'},
}]
}
As you can see, this json data contains an array of phones.
I used knockout mapping plugin and I can bind the 'name', 'email' and loop the phone numbers in a 'foreach: phones' with no hassle until I try to make a ko.compute on the phoneNumber which is an object in the array phones.
@section scripts
{
<script src="~/ViewModels/ContactModel.js"></script>
<script type="text/javascript">
var viewModel = new ContactModel(@Html.Raw(Model.ToJson()));
$(document).ready(function () {
ko.applyBindings(viewModel);
});
</script>
<label>Name</label><input data-bind="value: name" />
<label>Email</label><input data-bind="value: email" />
<label>Phones</label>
<table>
<tbody data-bind="foreach: phones">
<tr>
<td><strong data-bind='text: phoneType'></strong></td>
<td><input data-bind='value: phoneNumber' /></td>
</tr>
/tbody>
</table>
This is ContactModel.js
var ContactModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.reformatPhoneNumber = ko.computed(function(){
var newnumber;
newnumber = '+(1)' + self.phones().phoneNumber;
return newnumber;
});
};
For visual representation this is how this looks right now:
Name: John
Email: [email protected]
Phones:
<--foreach: phones -->
Home Phone: 999-888-777
Business Phone: 444-888-777
What Im trying to do is to reformat the phoneNumber to display it this way:
Name: John
Email: [email protected]
Phones:
<--foreach: phones -->
Home Phone: (+1)999-888-777
Business Phone: (+1)444-888-777
I try to do it by using the reformatPhoneNumber in place of phoneNumber in my binding like this:
<table>
<tbody data-bind="foreach: phones">
<tr>
<td><strong data-bind='text: phoneType'></strong></td>
<td><input data-bind='value: $root.reformatPhoneNumber' /></td>
</tr>
/tbody>
</table>
But when I do, the value of reformatPhoneNumber doesn't appear.
I read somewhere here that I have to make the objects inside my observableArray also observable because ko.mapping doesn't do that by default. But I cannot picture how to do it as I was expecting ko.mapping plugin to do all the job automatically for me as I am new to this jslibrary.
Any help would be greatly appreciated. Thank you very much!!
self.phones().phoneNumberrefer to, exactly?selfin your case? Please post a minimal but complete example. StackOverflow has the tools to include a runnable example right inside your question.