I'm using KnockOut mapping fromJS to create my View Model from a JSON object like the following:
{
"cats": [{
"name": "fluffy",
"color": "brown",
"kittens": [{
"name": "spot",
"color": "brown"
}, {
"name": "rascal",
"color": "grey"
}, {
"name": "trouble",
"color": "white"
}]
}, {
"name": "kitty",
"color": "red",
"kittens": [{
"name": "lady",
"color": "red"
}, {
"name": "skat",
"color": "striped"
}]
}]
}
html:
<div data-bind="foreach:cats">
<span data-bind="text:name"></span>
<table>
<tr data-bind="foreach: kittens">
<td data-bind="text:name"></td>
<td data-bind="text:color"></td>
<td><a data-bind="click: $parent:showParentColor" href="#">Parent Color</a></td>
</tr>
</table>
</div>
Javascript:
var KittenModel = function (data) {
ko.mapping.fromJS(data, {}, this);
// ... various computed values added to this
}
var mapping = {
'kittens': {
create: function(options) {
return new KittenModel(options.data);
}
},
'otherItem': {
create: function(options) {
return ('otherStuff');
}
}
}
var data = { ... }; // the JSON above
var CatsViewModel = ko.mapping.fromJS(data, mapping);
Question:
Where and how do I put the showParentColor() function so that the the data-bind works in the kitten table? For example:
function showParentColor(cat) {
alert(cat.color);
}
Thanks!