Last active
August 29, 2015 14:06
-
-
Save demius/b1e6993d047408ba8aa6 to your computer and use it in GitHub Desktop.
KnockoutJS drag-drop binding extension
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.drag = { | |
_dragging: false, | |
init: function (element, valueAccessor, allBindingsAccessor, data, context) { | |
$(element).attr('draggable', 'true'); | |
$(element).on('dragstart', function(e) { | |
// Payload (assumed to be a viewmodel) is converted to a plain JSON object | |
var d = ko.unwrap(valueAccessor()); | |
e.originalEvent.dataTransfer.setData("application/json", ko.toJSON(d)); | |
this._dragging = true; | |
}); | |
$(element).on('dragend', function (e) { | |
e.preventDefault(); | |
this._dragging = false; | |
}); | |
} | |
}; | |
ko.bindingHandlers.drop = { | |
init: function (element, valueAccessor, allBindingsAccessor, data, context) { | |
$(element).on('dragover', function (e) { | |
e.preventDefault(); | |
// highlight the element or something | |
}); | |
$(element).on('drop', function (e) { | |
var options = ko.unwrap(valueAccessor()); | |
var json = e.originalEvent.dataTransfer.getData("application/json"); | |
if (options.action) { | |
// NOTE: The knockout mapping extension is required to convert the JSON payload back into a viewmodel | |
options.action(ko.mapping.fromJSON(json)); | |
} | |
e.preventDefault(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment