Drag and drop target separate from Sortable contai

2019-08-25 20:29发布

问题:

I'm trying to set up drag and drop cloning with Knockout and jQuery, but I can't figure this bit out.
I have the knockout-sortable binding that Niemeyer wrote, but I can't find a way to hook it up how I'd like.

I was hoping the connectClass would be able to "catch" drops and pass them into the child element Sortable, but apparently not. Here's a fiddle I forked from Niemeyer that shows pretty simply what I'm trying to do.

http://jsfiddle.net/Kal_Torak/g74xN/3/

My Sortable bound elements aren't always going to have items in them, so the list itself won't be visible, so I need to be able to drop anywhere on the parent container and have them added as you'd expect.

回答1:

One option would be to add a little droppable binding that plays nice with the sortable and draggable bindings. There are a few ways that you could do it, but here is one way where you pass a handler to droppable and it calls the handler passing the new item as the first argument.

ko.bindingHandlers.droppable = {
    init: function(element, valueAccessor) {
        var dropHandler = valueAccessor() || {};

        $(element).droppable({
            drop: function(event, ui) {
               var item = ko.utils.domData.get(ui.draggable[0], "ko_dragItem");

                if (item) {
                    item = item.clone ? item.clone() : item;
                    dropHandler.call(this, item, event, ui);
                }
            }
        });
    }
};

Then, you would bind it like:

<div id="main" data-bind="droppable: addTask">

With addTask pushing to your observbaleArray.

Sample here: http://jsfiddle.net/rniemeyer/3JBnh/