Skip to content

Instantly share code, notes, and snippets.

@scottmessinger
Created December 31, 2011 21:58
Show Gist options
  • Save scottmessinger/1545466 to your computer and use it in GitHub Desktop.
Save scottmessinger/1545466 to your computer and use it in GitHub Desktop.
sortable lists in knockout.js
ko.bindingHandlers.sortableList = {
init: function(element, valueAccessor, allBindingsAccessor, context) {
var parent = allBindingsAccessor().parent
var list = valueAccessor();
$(element).sortable({
handle : '.move'
,start: function(){ mpq.track("sort")}
,sort: function(){
var $lis = $(this).children('li');
$lis.each(function(){
var $li = $(this);
var hindex = $lis.filter('.ui-sortable-helper').index();
if( !$li.is('.ui-sortable-helper') ){
var index = $li.index();
index = index < hindex ? index + 1 : index;
$li.val(index);
if( $li.is('.ui-sortable-placeholder') ){
$lis.filter('.ui-sortable-helper').val(index);
}
}
});
}
,update: function(event, ui) {
//retrieve our actual data item
var item = ko.dataFor(ui.item[0]);
//figure out its new position
var position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);
//remove the item and add it back in the right spot
if (position >= 0) {
list.remove(item);
list.splice(position, 0, item);
}
ui.item.remove();
parent.save(App.VMs.course)
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment