我正在尝试使用Knockout JS拖放,但无法使其正常工作。有什么建议吗?
<td data-bind="event: {ondrop: $root.HandleDrop}">
答案 0 :(得分:2)
如评论中所述,您必须创建自定义绑定处理程序才能实现此目的
查看型号:
(function() {
var _dragged;
ko.bindingHandlers.drag = {
init: function(element, valueAccessor) {
var dragElement = $(element);
var dragOptions = {
helper: 'clone',
revert: true,
revertDuration: 0,
start: function() {
_dragged = ko.utils.unwrapObservable(valueAccessor().value);
},
cursor: 'default'
};
dragElement.draggable(dragOptions).disableSelection();
}
};
ko.bindingHandlers.drop = {
init: function(element, valueAccessor) {
var dropElement = $(element);
var dropOptions = {
drop: function(event, ui) {
valueAccessor().value(_dragged);
}
};
dropElement.droppable(dropOptions);
}
};
})();
var ViewModel = function () {
var self = this;
self.user = ko.observableArray([{name:'jhon'},{name:'charlie'},{name:'jack'}]);
self.movedArray=ko.observableArray()
self.latestone = ko.computed({
read: function() {
return self.movedArray().length ? self.movedArray()[0] : "";
},
write: function(value) {
self.movedArray.unshift(value); // adds as first element in array
},
owner: self
});
};
$(function() {
ko.applyBindings(new ViewModel());
});
查看:
<ul id="dragbox" data-bind="foreach:user">
<li data-bind="text:$data.name,drag:{value:$data.name}"></li>
</ul>
<hr/>
<div id="dropbox" data-bind="drop: {value: latestone}">
<div data-bind="visible:(!!latestone())">
<p >Thanks for adding <span data-bind="text:latestone"></span>!</p>
<span>So far, you've added:</span>
<ul data-bind="foreach: movedArray">
<li data-bind="text: $data"></li>
</ul>
</div>
</div>
<hr/>
工作小提琴 here
致wilsonhut
的信用我只是分道扬.. - / p>