Reputation: 8266
Ok before I show my code and my approach let me explain what the problem at hand is, maybe someone has a better solution. The thing is that I have a list of arrays that are grouped a certain criteria. I need to render a list/section per criteria, and each section contains a list of objects that should also be rendered as HTML.
I'm new to KnockoutJS - I started using it yesterday. But given the problem at hand, I searched the docs for an observable dictionary or anything similar. Luckily, I found the ko.observableDictionary plugin. So I thought this should do the trick and wrote the following code (just some proof of concept):
<div id="tiles-holder" data-bind="template: { name: 'tile-list', foreach: dictionary }">
</div>
<script type="text/html" id="tile-list">
<div class="md-auto-max-width">
<div class="md-list-tiles md-auto-arrange-tiles" data-bind="template: { name: 'tile-default', foreach: items }"></div>
</div>
</script>
<script type="text/html" id="tile-default">
<div class="metro-tile-square md-list-item md-list-tile-large">
<div class="md-list-item-image" data-bind="css: { defaultimage: $data.title() != 'architect' }"></div>
<div>
<span data-bind="text: name"></span> - <span data-bind="text: $data.department"></span>
</div>
</div>
</script>
<script type="text/javascript" src="@Url.Content("~/Scripts/metro/ko.observableDictionary.js")"></script>
<script type="text/javascript">
$(function () {
var viewModel = function TileViewModel() {
var self = this;
self.dictionary = new ko.observableDictionary();
for (var i = 0; i < 15; i++) {
self.dictionary.push("Developers", new employee('developer' + i, 'developer', 'projectDevelopment'));
self.dictionary.push("Analysts", new employee('analyst' + i, 'analyst', 'business intelligence'));
}
self.dictionary.push("Architects",new employee('Some Architect', 'architect', 'Architecture and development'));
function employee(name, title, department) {
this.name = ko.observable(name);
this.title = ko.observable(title);
this.department = ko.observable(department);
}
};
ko.applyBindings(new viewModel(), $('#tiles-holder').get(0));
});
</script>
But I keep getting the following error:
Error: Unable to parse bindings. Message: TypeError: $data.title is not a function; Bindings value: css: { defaultimage: $data.title() != 'architect' }
I believe the problem is that $data
does not refer to the data context of the template. But how do I solve this?
Upvotes: 0
Views: 833
Reputation: 17554
Why use a dictionary in the first place, you are not using it as a dictionary so use a observableArray instead
anyway, you need to access the value prop of each item
Upvotes: 1