Dojo拖放问题:对目标DND容器中的项目进行排序

时间:2012-04-30 11:26:17

标签: javascript dojo drag-and-drop dojo-dnd

我的JavaScript代码如下

//我有一个Json:

var jsonRoles = {"roles": [
                            {"roleId": "1", "roleName": "role1", "roleDesc": "This is role1"},
                            {"roleId": "2", "roleName": "role2", "roleDesc": "This is role2"},
                            {"roleId": "3", "roleName": "role3", "roleDesc": "This is role3"}
                        ]
                    };

//要获取DND容器中列出的所有角色名称,我使用了for循环:

var results="";
                    for(var i=0;i<jsonRoles.roles.length;i++){
                        results += '<div class="dojoDndItem">' + jsonRoles.roles[i].roleName  + '</div>';
                    }

//拖放的两个内容窗格如下所示

var assignPermissionToUser1 = new dijit.layout.ContentPane({
                        //splitter:true,
                        region: "left",
                        style: "background-color: white;width: 200px; height: 500px",
                        content:'<div>' + '<label>Roles</label>' + '</div>' + '<div dojoType="dojo.dnd.Source" id="rolelistNode" class="container">' + 
                                '<div dojoType="dojo.dnd.Source" class="dojoDndItem movableContainer">' + '</div>' + results +
                                '</div>'       
                    });
                    var assignPermissionToUser2 = new dijit.layout.ContentPane({
                        //splitter:true,
                        region: "right",
                        style: "background-color: white;width: 200px; height: 500px",
                        content:'<div>' + '<label>Users</label>' + '</div>' +'<div dojoType="dojo.dnd.Source" class="container">' +
                                '<div dojoType="dojo.dnd.Source" class="dojoDndItem movableContainer">' + '</div>' +
                                '</div>'            
                    });

//边框容器

            innerBorderContainerAsAccordion = new dijit.layout.BorderContainer({
                id: "innerBorderContainerAsAccordion",
                region: "center",
                style: "background-color: white;width: 175px; height: 550px"
            });

//设置边框容器的内容

    innerBorderContainerAsAccordion.addChild(assignPermissionToUser1);
    innerBorderContainerAsAccordion.addChild(assignPermissionToUser2);

我的问题是,如果我将一个元素从DND容器拖到另一个容器上,它如何按ID或字母等排列/排序项目?

例如(下图)

两个容器的初始状态 enter image description here

将一些项目拖放到第二个DND容器 enter image description here

如何强制对第二个DND容器的项目进行完全排序,如下所示: enter image description here

有人可以帮忙吗?谢谢

3 个答案:

答案 0 :(得分:1)

请尝试此代码,这次是javascript

 function sortList(listId) {
        // Get the ul object
        var oUl = document.getElementById(listId);
        /* Perform a Bubble Sort on the list items */
        for (var i in oUl.childNodes) {
            var x = oUl.childNodes[i];
            for (var j in oUl.childNodes) {
                var y = oUl.childNodes[j];
                if ((x.innerText != 'undefined' || y.innerText != 'undefined') && x.innerText > y.innerText) {
                    // Skip if x is already the first list item
                    if (oUl.firstChild != x)
                        oUl.insertBefore(y, x);
                }
            }
        }

    }

    /* Define innerText for Mozilla based browsers */
    if ((typeof HTMLElement != 'undefined') && (HTMLElement.prototype.__defineGetter__ != 'undefined')) {
        HTMLElement.prototype.__defineGetter__("innerText", function () {
            var r = this.ownerDocument.createRange();
            r.selectNodeContents(this);
            return r.toString();
        });

    }


    window.onload = function () {
        sortList("ID_of_Your_ul_tag");
    }

答案 1 :(得分:1)

首先,您的dndContainer具有className dojoDndItem,如果您不对“真实项目”应用唯一的className以区分它们与父项的区别,则会失败。

我不知道为什么,但你创建4 x dndSource(movingContainer?)

最佳做法是给你的dndContainer一个ID,假设项目有一个类=='roleItem',dndContainer有id =='targetContainer'

var dndC = dojo.byId('targetContainer', assignPermissionToUser2.domNode);
dojo.query( ".roleDndItem",  dndC )
  .sort(function( a,b ) {
      // can check for whatever property on the item here
      // for complete numerical sort you need a comperator (parseFloat works)
      return (a.innerHTML == b.innerHTML 
          ? 0 : (a.innerHTML > b.innerHTML ? 1 : -1));
  })
  .forEach(function(a, idx) {
      console.log(a.innerHTML);  // output should be alphanumerically 
      // sorted by lowest == (idx=0)
      // idx 0 inserts be childNode[0] (firstChild), 
      // idx 1 before (new) second child
      dndC.insertBefore(a, dndC.childNodes[idx]);
});

Dojo发布了似乎是oneliner的东西,但它更多的是它。但是,您只需要调整两行,sort-return和node-reference dndC。

dojo.query(".roleItem",  dndC ).sort(
    function( a,b ) {  
        return (a.innerHTML == b.innerHTML ? 0 : (a.innerHTML > b.innerHTML ? 1 : -1));
    }
).forEach(
    function(a, idx) { 
        dndC.insertBefore(a, dndC.childNodes[idx]);  
}); //^^

连接做类似于

的事情
dojo.subscribe("dnd/drop", function() { /* */ });

或以编程方式创建的dndSource;

dojo.connect(dndSourceObj, "onDrop", function() { /* */ });

答案 2 :(得分:0)

试试这段代码:

jQuery.fn.sortElements = (function(){
    var sort = [].sort;
    return function(comparator, getSortable) {
        getSortable = getSortable || function(){return this;};
        var placements = this.map(function(){     
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );     
            return function() {
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }     
                parentNode.insertBefore(this, nextSibling);
                parentNode.removeChild(nextSibling);
            };
        });
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
    };
})();

假设以下标记:

<ul>
    <li>Banana</li>
    <li>Carrot</li>
    <li>Apple</li>
</ul>

您可以按字母顺序对项目进行排序:

$('li').sortElements(function(a, b){
    return $(a).text() > $(b).text() ? 1 : -1;
});

这将导致:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Carrot</li>
</ul>