Created
September 22, 2020 15:24
-
-
Save smailliwcs/45a4de591b293289e461b5bbb72e29ec to your computer and use it in GitHub Desktop.
Knockout binding handler: sortable
This file contains 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
<script type="text/javascript"> | |
ko.bindingHandlers.sortable = { | |
normalize: function (valueAccessor) { | |
var value = ko.unwrap(valueAccessor()); | |
if (typeof value === "object" && "data" in value) { | |
return value; | |
} else { | |
return { data: valueAccessor() }; | |
} | |
}, | |
getHandlers: function (data) { | |
var startIndex; | |
return { | |
start: function (event, ui) { | |
startIndex = ui.item.index(); | |
}, | |
stop: function (event, ui) { | |
var stopIndex = ui.item.index(); | |
ui.item.remove(); | |
var item = data.splice(startIndex, 1)[0]; | |
data.splice(stopIndex, 0, item); | |
} | |
}; | |
}, | |
init: function (element, valueAccessor) { | |
var self = ko.bindingHandlers.sortable; | |
var value = self.normalize(valueAccessor); | |
var handlers = self.getHandlers(value.data); | |
var options = $.extend({}, ko.unwrap(value.options), handlers); | |
$(element).sortable(options); | |
return ko.bindingHandlers.foreach.init.apply(this, arguments); | |
}, | |
update: function () { | |
ko.bindingHandlers.foreach.update.apply(this, arguments); | |
} | |
}; | |
</script> | |
<ul data-bind="sortable: letters"> | |
<li data-bind="text: $data"></li> | |
</ul> | |
<button type="button" data-bind="click: add">Add</button> | |
<ul data-bind=" | |
sortable: { | |
data: numbers, | |
options: { | |
handle: '.handle', | |
cancel: '' | |
} | |
}"> | |
<li> | |
<button type="button" class="handle">Move</button> | |
<span data-bind="text: $data"></span> | |
</li> | |
</ul> | |
<script type="text/javascript"> | |
function ViewModel() { | |
var self = this; | |
self.letters = ko.observableArray(["a", "b", "c"]); | |
self.numbers = ko.observableArray(); | |
self.add = function () { | |
self.numbers.push(self.numbers().length + 1); | |
}; | |
} | |
ko.applyBindings(new ViewModel()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment