Last active
August 29, 2015 14:07
-
-
Save jbreckmckye/106d151c3f23746f40a2 to your computer and use it in GitHub Desktop.
Knockout simple sorted forEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<h4>Simple foreach</h4> | |
<ul data-bind="foreach: names"> | |
<li>Value: <span data-bind="text: $data"></span></li> | |
</ul> | |
<h4>Sorted foreach</h4> | |
<ul data-bind="foreachSorted: names"> | |
<li>Value: <span data-bind="text: $data"></span></li> | |
</ul> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ko.bindingHandlers.foreachSorted = { | |
init : function(element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var sortedNames = sortObservedArray(valueAccessor); | |
ko.bindingHandlers.foreach.init(element, function () { return sortedNames; }, allBindings, viewModel, bindingContext); | |
return {controlsDescendantBindings: true}; | |
}, | |
update : function(element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var sortedNames = sortObservedArray(valueAccessor); | |
ko.bindingHandlers.foreach.update(element, function () { return sortedNames; }, allBindings, viewModel, bindingContext); | |
} | |
}; | |
function sortObservedArray(valueAccessor) { | |
var plainArray = ko.utils.unwrapObservable(valueAccessor()); | |
return plainArray.sort(); | |
} | |
function ViewModel() { | |
this.names = ['gamma 7','beta 5','beta 6','beta 3','alpha', 'delta 44']; | |
} | |
ko.applyBindings(new ViewModel()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment