Reputation: 4592
Probably a trivial question for some. I have a view model for my objects that looks like so:
this.Activities = ko.observableArray([
{ "date": "28/11/2012 00:00:00",
"activities": [
{ "company": "BOW",
"description": "Backup Checks",
"length": "60"
},
{ "company": "AMS",
"description": "Data Request",
"length": "135"
},
]},
{ "date": "30/11/2012 00:00:00",
"activities": [
{ "company": "BOW",
"description": "Backup Checks",
"length": "60"
},
{ "company": "SLGT",
"description": "Software Development",
"length": "240"
},
{ "company": "BOW",
"description": "Data Request",
"length": "30"
},
]},
]);
I want to build an accordion which will hide activities arrays and will display dates. Whenever a date is clicked a list of activites matching this date will be presented by expanding appropriate panel below. Now, in the project I don't use Knockout.js for, I just use Id of a general Activity object to link ID attribute of accordion header with a name attribute in accordion body element. I use Model properties in the strongly typed view to achieve that. Since in the Knockout.js I feed a view model with the details of the Activities I have limited control over the structure of Html being created while data-binding. How can I link accordion headers with matching body elements then?
Upvotes: 4
Views: 5948
Reputation: 7013
This assumes you are using the bootstrap accordions but should give you a good idea of how to do it with any accordion system.
http://jsfiddle.net/billpull/f8Cbb/1/show/
HTML
<div class="accordion" id="accordion2" data-bind="foreach: {data: Activities, as: 'activity'}">
<!-- ko template: 'accordionTmpl' --><!-- /ko -->
</div>
<script type="text/html" id="accordionTmpl">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" data-bind="text: activity.date, attr: { href: '#' + activity.order}"></a>
</a>
</div>
<div class="accordion-body collapse" data-bind="attr: { id: activity.order}">
<div class="accordion-inner">
<ul data-bind="foreach: {data: activity.activities, as: 'subActivity'}">
<li>
<span data-bind="text: subActivity.company"></span><br>
<span data-bind="text: subActivity.description"></span><br>
<span data-bind="text: subActivity.length"></span>
</li>
</ul>
</div>
</div>
</div>
</script>
Javascript
var ViewModel = function () {
this.Activities = ko.observableArray([
{ "date": "28/11/2012 00:00:00",
"order" : 1,
"activities": [
{ "company": "BOW",
"description": "Backup Checks",
"length": "60"
},
{ "company": "AMS",
"description": "Data Request",
"length": "135"
},
]},
{ "date": "30/11/2012 00:00:00",
"order" : 2,
"activities": [
{ "company": "BOW",
"description": "Backup Checks",
"length": "60"
},
{ "company": "SLGT",
"description": "Software Development",
"length": "240"
},
{ "company": "BOW",
"description": "Data Request",
"length": "30"
},
]},
]);
};
$(function () {
ko.applyBindings(new ViewModel());
});
Upvotes: 5