KnockoutJS Sorting
HTML
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/knockout-latest.debug.js"></script>
<ul data-bind="foreach: choices">
<li>
<h2 data-bind="text: $data"></h2>
<ul data-bind="foreach: $root.people.index.type()[$data]">
<li data-bind="text: name"></li><span data-bind="text: url"></span>
</ul>
<hr/>
</li>
</ul>
<a href="#" data-bind="click:sort">
Sort
</a>
CSS
table {
padding: 0px;
margin: 0px;
border-spacing: 0px;
width: 100%;
}
.body {
max-width: 230px;
min-width: 210px;
border: 1px solid #231F20;
border-radius: 10px;
background: #ADAFB2;
/*padding: 10px 6px;*/
color: #58595B;
font-family: 'Ubuntu', sans-serif;
}
.issueContainer {
border: 1px solid #231F20;
border-radius: 2px;
height: 226px;
overflow-y: auto;
background: #E9E9EA;
margin: 10px 6px;
color: #231F20;
font-weight: lighter;
font-size: 12px;
}
.issue {
border-bottom: 1px solid #B1B3B6;
padding: 4px;
}
.issueText {
padding-left: 5px;
width: 100%;
vertical-align: middle !important;
}
JavaScript
ko.observableArray.fn.distinct = function(prop) {
var target = this;
target.index = {};
target.index[prop] = ko.observable({});
ko.computed(function() {
//rebuild index
var propIndex = {};
ko.utils.arrayForEach(target(), function(item) {
var key = ko.utils.unwrapObservable(item[prop]);
if (key) {
propIndex[key] = propIndex[key] || [];
propIndex[key].push(item);
}
});
target.index[prop](propIndex);
});
return target;
};
var Person = function(name,url, type) {
this.name = ko.observable(name);
this.url = ko.observable(url);
this.type = ko.observable(type);
}
var ViewModel = function() {
var self = this;
this.choices = ["Friend", "Enemy", "Other" ];
this.people = ko.observableArray([
new Person("Jimmy","url1", "Enemy"),
new Person("George", "url2","Friend"),
new Person("Zippy","url3", "Enemy"),
new Person("Albert","url4", "Friend"),
new Person("Zippi","url5", "Enemy"),
new Person("Hilton","url6", "Enemy")
]).distinct('type');
this.sort = function(person) {
self.people.sort(function (l, r) { return l.name() > r.name() ? 1 : -1 })
};
};
ko.applyBindings(new ViewModel());