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!
Note: I like the other answer's approach better than this one, but did want to present an alternative solution for the sake of having multiple options.
Alternative 1
You could create a "static" method in your
KittenModel
that logs any cat's color that it's passed:Now, because your view has access to the parent-child structure, you can call this method with any parent you want:
An example:
Alternative 2
In the factory function you're passing as an options, you have both
data
andparent
available:options.data
holds the item being currently mapped.options.parent
in this case will refer to the parentcat
. I haven't tested this, but this might work:You may use one of the following based on your view model hierarchy :
$parents array : This is an array which contains all your view models.
$parents[0] : The parent view model context.(also it’s the same as
$parent
)$parents[1]: The second parent view model context.(grand parent)
$parents[2]: The third parent view model context . (great-grand parent)
Update : If you want to add a function in
CatsViewModel
level, you simply add your function to created model.Example :https://jsfiddle.net/kyr6w2x3/87/
JS:
View:
Below is the hierarchy of your model
Alternative : You can do the job yourself and create your models.Would be easier for you to modify and maintain based on what you want.You can also add
click
function inside any models you want.Example :http://jsfiddle.net/kyr6w2x3/91/
HTML :
JS: