Dynamically specifying the name of a template
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<input type="radio" name="choices" value="summary" data-bind="checked: selectedView" />Summary
<input type="radio" name="choices" value="details" data-bind="checked: selectedView" />Details
<hr/>
<div data-bind="component: selectedView()"></div>
CSS
h2 { font-weight: bold; }
p { font-size: .8em; }
div { padding-bottom: 20px; }
JavaScript
function viewModel(){
var self = this;
self.articles = [];
self.selectedView = ko.observable("summary");
self.selectedArticle = ko.observable();
self.loadArticles = function(){
console.log("loading data");
//simulating the $.get to the API
self.articles = [{
id: 1,
title: "Article One",
content: "Content for article one."},
{
id: 2,
title: "Article Two",
content: "Content for article two."},
{
id: 3,
title: "Article Three",
content: "Content for article three."
}];
}
self.loadArticles();
}
ko.components.register('summary', {
viewModel: viewModel,
template: '<div data-bind="foreach: articles"><div data-bind="text: title"></div></div>'
});
ko.components.register('summary2', {
viewModel: viewModel,
template: '<div data-bind="foreach: articles"><div data-bind="text: title"></div></div>'
});
ko.components.register('summary3', {
viewModel: viewModel,
template: '<div data-bind="foreach: articles"><div data-bind="text: title"></div></div>'
});
ko.components.register('details', {
viewModel: viewModel,
template: '\
<div data-bind="foreach: articles">\
<div>\
<h2 data-bind="text: title"></h2>\
<p data-bind="text: content"></p>\
<button data-bind="click: $parent.selectedArticle">Edit</button>\
</div>\
</div>'
});
ko.applyBindings(new viewModel());