KO Component with children Test V2
KO v3.2 base
by Retsam19
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.debug.js"></script>
<parent></parent>
<template id='parent-template'>
<!-- ko foreach: children -->
<child params="viewModel: $data"></child>
<br />
<!-- /ko -->
</template>
<template id='child-template'>
<span data-bind="
text: text,
click: onClick
"></span>
</template>
JavaScript
function ParentVM() {
var self = this;
var callback = function (message) {
alert(message);
}
self.children = ["foo", "bar"].map(function (text) {
return new ChildVM(text, callback);
});
}
function ChildVM(text, callback) {
var self = this;
self.text = text;
self.onClick = function () {
callback(text + " clicked");
}
}
vm = {};
ko.components.register("parent", {
viewModel: ParentVM,
template: {
element: 'parent-template'
}
});
ko.components.register("child", {
viewModel: {
createViewModel: function(params, componentInfo) {
return params.viewModel;
}
},
template: {
element: 'child-template'
}
});
ko.applyBindings(vm);