JSFiddle - React, Tailwind, and code Playground
by Bryan Dellinger
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js"></script>
<ul class="list-inline" data-bind="foreach:uniquetags">
<li data-bind="text:$data, click: $parent.setSelected"></li>
</ul>
<ul data-bind="foreach:filteredNames">
<li><span data-bind="text:name"></span>
<ul data-bind="with: location">
<li data-bind="text: 'Lat: ' + lat()"></li>
<li data-bind="text: 'Long: ' + long()"></li>
</ul>
</li>
</ul>
JavaScript
function loc(d) {
var self = this;
this.lat = ko.observable(d.lat);
this.long = ko.observable(d.long);
}
function point(tag, name, location) {
var self = this;
this.tag = ko.observable(tag);
this.name = ko.observable(name);
this.location = new loc(location);
}
function viewModel() {
var self = this;
this.points = ko.observableArray('');
this.selectedPoint = ko.observable('');
this.setSelected = function(item) {
self.selectedPoint(item);
}
this.justtags = ko.computed(function() {
var tags = ko.utils.arrayMap(this.points(), function(item) {
return item.tag();
});
return tags.sort();
}, this);
this.uniquetags = ko.dependentObservable(function() {
return ko.utils.arrayGetDistinctValues(self.justtags()).sort();
}, this);
this.filteredNames = ko.computed(function() {
var filter = self.selectedPoint()
if (!filter) {} else {
return ko.utils.arrayFilter(this.points(), function(item) {
if (item.tag() === filter) {
return item
};
});
}
}, this);
}
var data = [{
tag: "places",
name: "Dubai Marina",
location: {
lat: 10,
long: 20
}
}, {
tag: "places",
name: "Burj Khalifa",
location: {
lat: 20,
long: 30
}
}, {
tag: "Coffee",
name: "StarBucks",
location: {
lat: 30,
long: 40
}
}, {
tag: "Coffee",
name: "Costa",
location: {
lat: 50,
long: 60
}
}, {
tag: "Club",
name: "Beach Club",
location: {
lat: 70,
long: 80
}
}, {
tag: "Club",
name: "Cheers Club",
location: {
lat: 90,
long: 100
}
}];
var vm = new viewModel();
$(document).ready(function() {
ko.applyBindings(vm);
$.each(data, function(i, item) {
vm.points.push(new point(item.tag, item.name, item.location))
})
console.log(ko.toJS(vm));
})