anontemplate
HTML
<script src="https://raw.github.com/jquery/jquery-tmpl/master/jquery.tmpl.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js"></script>
<div class="topicDetail" data-bind="with: activeTopic">
<ul class="querylist" data-bind="foreach: queries">
<li class="query">
<span class="querylink" data-bind="text: text, click: select"></span>
<span class="nResults" data-bind="text: nHits"></span>
</li>
</ul>
<div>Active query: <span data-bind="text: activeQueryText"></span></div>
</div>
CSS
.query{
list-style-type:none;
}
.nResults {
font-weight: bold;
}
JavaScript
var Topic = function(title, queries) {
var self = this;
this.title = ko.observable(title);
this.toString = function() { return this.title(); };
this.queries = ko.observableArray(queries);
this.activeQuery = ko.observable();
this.view = null;
$.each(queries, function(i,q) {
console.log(q);
q.topic = self;
});
this.activeQueryText = ko.dependentObservable(function() {
var query = this.activeQuery();
return query ? query.text() : 'None selected';
}, this);
return this;
};
var queryId = 1;
var Query = function(text, n) {
this.id = ko.observable(queryId++);
this.text = ko.observable(text);
this.nHits = ko.observable(n);
this.topic = null;
this.select = function() {
this.topic.activeQuery(this);
};
return this;
};
var queries = ko.observableArray([
new Query('some search', 100),
new Query('Another search', 50),
new Query('This is the good one', 25)
]);
var topic = new Topic('test', queries);
var viewModel = function(topic) {
this.activeTopic = ko.observable(topic);
topic.view = this;
};
ko.applyBindings(new viewModel(topic));