I'm trying to get my observableArray to alphabetically sort with the addition of a new item to the list when clicking "sort". Can anyone shed some light on what i'm doing wrong here?
Thank you,
Jason
........................
https://jsfiddle.net/jaloomis111/tssLxbo0/
<input data-bind="value: inputName, valueUpdate: 'afterkeydown'" type="text"/>
<ul data-bind="foreach: myFamily"/>
<li data-bind="text: name"></li>
</ul>
<button data-bind="click: addItem">add item</button>
<button data-bind="click: sortArray">sort array</button>
$(function(){
var data = [
{name: 'Jason'},
{name: 'Alexi'},
{name: 'Gabi'}
];
viewModel = {
inputName: ko.observable(""),
myFamily : ko.observableArray(data),
//addItem : function(){
//this.myFamily.push({name: this.inputName()});
//this.inputName("");
//},
addItem : function() {
this.myFamily.push({name: this.inputName()});
},
removeItem : function(){
this.myFamily.pop();
},
sortArray : function(){
this.myFamily.sort(function (left, right) {
return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1)
})
},
};
ko.applyBindings(viewModel);
});
The sort function does not operate on the array that is passed it, but instead returns a new sorted version of the array. So to update your observable with the sorted result you need to set its contents to the sort result.
sortArray : function(){
this.myFamily(this.myFamily().sort(function (left, right) {
return left.name.toLowerCase() == right.name.toLowerCase() ? 0 : (left.name.toLowerCase() < right.name.toLowerCase() ? -1 : 1)
}));
}
Currently your sort function is case sensitive, and I'm guessing you don't want that either. Capitalized names would always float up above non capitalized names.
Edit: Whoops, you're using knockout's .sort() on the observable not javascript's sort on the array so you can disregard the first part of my answer. It's probably just the casing thing.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments