拖放列表 - 双击删除项目

时间:2014-04-10 09:28:08

标签: knockout.js

是否可以添加事件以从拖放列表中删除itom以及关联observableArray(使用sortable)?

我尝试使用与在多选列表中双击时删除相同的逻辑,但没有成功:

HTML:

<div class="list">
    <h2>Stored procedures In DB 2</h2>
    <ul class="list" data-bind="sortable: { data: storedProceduresInDB2, beforeMove: checkAndCopy }, event: { dblclick: removeFromDb2 }">
        <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.storedProceduresInDB2Orig = ko.observableArray([
        { Name: 'SP3', Id: 3 },
        { Name: 'SP4', Id: 4 }
    ]);
    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;
        }
    };

    self.removeFromDb2 = function(item, event){       
        self.storedProceduresInDB2.remove(function(item) {
            var nameToRemove = $(event.currentTarget).find("option:selected").text();
            var isOrig = ko.utils.arrayFirst(self.storedProceduresInDB2Orig(), function(item){
                return item.Name == nameToRemove;
            });
            return !isOrig && item.Name == nameToRemove;
        });
    }
};

ko.applyBindings(new ViewModel());

JSFiddle

1 个答案:

答案 0 :(得分:1)

双击LI不会使其被选中,因此找到nameToRemove的jQuery无法正确查找文本。相反,使用它(你可以在remove函数之外执行它,因为它只需要抓取一个:

var nameToRemove = $(event.target).text();

这是updated JSFiddle