可排序 - 将项目从列表拖放到另一个(复制)

时间:2014-04-08 12:07:25

标签: jquery knockout.js

我希望能够通过拖放选择多个项目并将复制从列表中复制到另一个(双向),并且只有在它不存在的情况下才会删除... < / p>

一些帮助将不胜感激。

编辑:关于查理的帖子和小提琴,如何才能选择多个项目拖放到另一个列表?就像现在一样,它只能同时允许1个项目。

HTML:

<div class="list">
    <h2>Stored procedures In DB 1</h2>
    <ul class="list" data-bind="sortable: { data: storedProceduresInDB1, beforeMove: checkAndCopy }">
        <li class="item" data-bind="text: Name"></li>
    </ul>
</div><br>

<div class="list">
    <h2>Stored procedures In DB 2</h2>
    <ul class="list" data-bind="sortable: { data: storedProceduresInDB2, beforeMove: checkAndCopy }">
        <li class="item" data-bind="text: Name"></li>
    </ul>
</div>

代码:

var ViewModel = function () {
    var self = this;
   self.storedProceduresInDB1 = ko.observableArray([
        { Name: 'SP1', Id: 1 },
        { Name: 'SP2', Id: 2 },
        { Name: 'SP3', Id: 3 }
    ]);
    self.storedProceduresInDB2 = ko.observableArray([
        { Name: 'SP3', Id: 3 },
        { Name: 'SP4', Id: 4 },
        { Name: 'SP5', Id: 5 }
    ]);
    self.selectedStoredProcedureInDB1 = ko.observable();
    self.selectedStoredProcedureInDB2 = ko.observable();
    self.selectStoredProcedureInDB1 = function (sp) {
        self.selectedStoredProcedureInDB1(sp);
    };
    self.selectStoredProcedureInDB2 = function (sp) {
        self.selectedStoredProcedureInDB2(sp);
    };
    self.checkAndCopy = function(event) {
        var targetHasItem = ko.utils.arrayFilter(event.targetParent(), function(item) {
            return item.Id == event.item.Id;
        }).length;
        if(!targetHasItem) {
            event.targetParent.splice(event.targetIndex, 0, event.item);
        }
        if(event.targetParent != event.sourceParent) {
            event.cancelDrop = true;
        }
    };
};

ko.applyBindings(new ViewModel());

Charlie's JSFiddle

2 个答案:

答案 0 :(得分:4)

注意:此答案仅允许一次排序一个项目。要一次排序多个项目,请参阅this solution

我建议使用Ryan Niemeyer的knockout-sortable绑定处理程序(https://github.com/rniemeyer/knockout-sortable),它处理了很多处理knockout和jQuery可以排序的怪癖。

如果使用knockout-sortable,您可以使用beforeMove回调取消放弃,并根据您的条件将副本添加到第二个列表。

JSFiddle working example,以下是相关部分:

<强> HTML

注意我们传入一个对象的可排序绑定,该对象指定用于列表的数据,以及用于beforeMove回调的方法。

<div class="list">
    <h2>Stored procedures In DB 1</h2>
    <ul class="list" data-bind="sortable: { data: storedProceduresInDB1, beforeMove: checkAndCopy }">
        <li class="item" data-bind="text: Name"></li>
    </ul>
</div>
<div class="list">
    <h2>Stored procedures In DB 2</h2>
    <ul class="list" data-bind="sortable: { data: storedProceduresInDB2, beforeMove: checkAndCopy }">
        <li class="item" data-bind="text: Name"></li>
    </ul>
</div>

<强>的JavaScript

我们将此方法添加到视图模型中以检查目标列表是否已包含该项目,如果不存在则复制该项目,然后取消drop事件以使原始项目保留在其原始列表中。

self.checkAndCopy = function(event) {
    var targetHasItem = ko.utils.arrayFilter(event.targetParent(), function(item) {
        return item.Id == event.item.Id;
    }).length;
    if(!targetHasItem) {
        event.targetParent.splice(event.targetIndex, 0, event.item);
    }
    // Only cancels drop if moving to new list to allow sorting within original list
    if(event.targetParent != event.sourceParent) {
        event.cancelDrop = true;
    }
};

答案 1 :(得分:3)

这是一个允许一次排序多个项目的解决方案。基于this related answer,但已修改为使用knockout.jsknockout-sortable

JSFiddle(在Chrome中测试):http://jsfiddle.net/QWgRF/715/

<强> HTML

为可排序项和列表项添加了ID,以便jQuery可排序代码可以确定正在选择哪些项。

添加了options属性,该属性将传递给基础jQuery Sortable插件。

为每个列表项添加了一个点击处理程序,供选择和多选。

<div class="list">
    <h2>Stored procedures In DB 1</h2>
    <ul class="list" id="sortableForDB_1" data-bind="sortable: {
      data: storedProceduresInDB1,
      beforeMove: checkAndCopy,
      options: multiSortableOptions }">
        <li class="item" data-bind="attr: { id: 'sp_'+Id }, text: Name,
          click: $root.selectProcedure.bind($data, $parent.storedProceduresInDB1()),
          css: { selected: Selected }">
        </li>
    </ul>
</div>
<div class="list">
    <h2>Stored procedures In DB 2</h2>
    <ul class="list" id="sortableForDB_2" data-bind="sortable:  {
      data: storedProceduresInDB2,
      beforeMove: checkAndCopy,
      options: multiSortableOptions }">
        <li class="item" data-bind="attr: { id: 'sp_'+Id }, text: Name,
          click: $root.selectProcedure.bind($data, $parent.storedProceduresInDB2()),
          css: { selected: Selected }">
        </li>
    </ul>
</div>

<强>的JavaScript

可排序选项。延迟150以允许点击处理程序用于选择。还原0因为动画看起来很奇怪我们如何搞乱列表和助手。

stop函数会重置导致列表html刷新的observableArray

helper函数会抓取所有选定的项目,并将它们添加到新的帮助程序标记中,以便直观地拖动多个项目。

var multiSortableOptions =  {
    delay: 150,
    revert: 0,
    stop: function(event, ui) {
        // Force lists to refresh all items
        var db1 = myViewModel.storedProceduresInDB1,
            db2 = myViewModel.storedProceduresInDB2,
            temp1 = db1(),
            temp2 = db2();
        ui.item.remove();
        db1([]);
        db1(temp1);
        db2([]);
        db2(temp2);
    },
    helper: function(event, $item) {
        // probably a better way to pass these around than in id attributes, but it works
        var dbId = $item.parent().attr('id').split('_')[1],
            itemId = $item.attr('id').split('_')[1],
            db = myViewModel['storedProceduresInDB'+dbId];

        // If you grab an unhighlighted item to drag, then deselect (unhighlight) everything else
        if(!$item.hasClass('selected')) {
            ko.utils.arrayForEach(db(), function(item) {
                if(item.Id == itemId) {
                    item.Selected(true);
                } else {
                    item.Selected(false);
                }
            });
        }

        // Create a helper object with all currently selected items
        var $selected = $item.parent().find('.selected');
        var $helper = $('<li class="helper"/>');
        $helper.append($selected.clone());
        $selected.not($item).remove();
        return $helper;
    }
};

查看模型。为每个存储过程添加了Selected可观察属性。添加了selectProcedure方法,根据点击次数和ctrl +点击次数更新新的Selected属性。

还对checkAndCopy方法进行了大量修改。我认为内联评论可以解释它是如何运作的。

var ViewModel = function () {
    var self = this;
    self.storedProceduresInDB1 = ko.observableArray([
        { Name: 'SP1', Id: 1, Selected: ko.observable(false) },
        { Name: 'SP2', Id: 2, Selected: ko.observable(false) },
        { Name: 'SP3', Id: 3, Selected: ko.observable(false) }
    ]);
    self.storedProceduresInDB2 = ko.observableArray([
        { Name: 'SP3', Id: 3, Selected: ko.observable(false) },
        { Name: 'SP4', Id: 4, Selected: ko.observable(false) },
        { Name: 'SP5', Id: 5, Selected: ko.observable(false) }
    ]);
    self.checkAndCopy = function(event) {
        var items;
        if(event.targetParent !== event.sourceParent) {
            // Get all items that don't yet exist in the target
            items = ko.utils.arrayFilter(event.sourceParent(), function(item) {
                return item.Selected() && !ko.utils.arrayFirst(event.targetParent(), function(targetItem) {
                    return targetItem.Id == item.Id;
                });
            });
            // Clone the items (otherwise the Selected observable is shared by the item in both lists)
            items = ko.utils.arrayMap(items, function(item) {
                var clone = ko.toJS(item);
                clone.Selected = ko.observable(true);

                // While we're here, let's deselect the source items so it looks cleaner
                item.Selected(false);

                return clone;
            });
            // Deselect everything in the target list now so when we splice only the new items are selected
            ko.utils.arrayForEach(event.targetParent(), function(item) {
                item.Selected(false);
            });
        } else {
            // Moving items within list, grab all selected items from list
            items = event.sourceParent.remove(function(item) {
                return item.Selected();
            });
        }

        // splice items in at target index
        items = items.reverse();
        for(var i=0; i<items.length; i++) {
            event.targetParent.splice(event.targetIndex, 0, items[i]);
        }

        // always cancel drop now, since we're manually rearranging everything
        event.cancelDrop = true;
    };
    self.selectProcedure = function(array, $data, event) {
        if(!event.ctrlKey && !event.metaKey) {
            $data.Selected(true);
            ko.utils.arrayForEach(array, function(item) {
                if(item !== $data) {
                    item.Selected(false);
                }
            });
        } else {
            $data.Selected(!$data.Selected());
        }
    };

};

添加了对View Model的全局引用,以便jQuery代码可以与它进行交互。

myViewModel = new ViewModel();

ko.applyBindings(myViewModel);