Подтвердить что ты не робот

Настройка контекстного меню jstree для контекстного меню для разных типов node

Я видел пример где-то в Интернете, показывающий, как настроить внешний вид контекстного меню jstree с помощью контекстного меню (с помощью контекстного меню).

Например, разрешите моим пользователям удалять "документы", но не "папки" (скрыв опцию "удалить" из контекстного меню для папок).

Теперь я не могу найти этот пример. Может кто-то указать мне верное направление? Официальное documentation действительно не помогло.

Edit:

Так как я хочу контекстное меню по умолчанию только с одним или двумя незначительными изменениями, я бы предпочел не воссоздать все меню (хотя, конечно, я буду, если это единственный способ). Я хотел бы сделать что-то вроде этого:

"contextmenu" : {
    items: {
        "ccp" : false,
        "create" : {
            // The item label
            "label" : "Create",
            // The function to execute upon a click
            "action": function (obj) { this.create(obj); },
            "_disabled": function (obj) { 
                alert("obj=" + obj); 
                return "default" != obj.attr('rel'); 
            }
        }
    }
}

но это не сработает - элемент создания всегда отключен (предупреждение никогда не появляется).

4b9b3361

Ответ 1

Плагин contextmenu уже имеет поддержку для этого. Из документации, к которой вы привязались:

items: ожидает объект или функцию, которая должна возвращать объект. Если функция используется, она запускается в контексте дерева и получает один аргумент - node, который был щелкнут правой кнопкой мыши.

Чтобы вместо contextmenu работать с жестко запрограммированным объектом, вы можете предоставить следующую функцию. Он проверяет элемент, который был нажат для класса с именем "папка", и удаляет элемент меню "удалить", удалив его из объекта:

function customMenu(node) {
    // The default set of all items
    var items = {
        renameItem: { // The "rename" menu item
            label: "Rename",
            action: function () {...}
        },
        deleteItem: { // The "delete" menu item
            label: "Delete",
            action: function () {...}
        }
    };

    if ($(node).hasClass("folder")) {
        // Delete the "delete" menu item
        delete items.deleteItem;
    }

    return items;
}

Обратите внимание, что приведенное выше полностью скроет параметр удаления, но плагин также позволяет вам отображать элемент при отключении его поведения, добавляя _disabled: true к соответствующему элементу. В этом случае вы можете использовать items.deleteItem._disabled = true в инструкции if.

Должно быть очевидным, но не забудьте инициализировать плагин с помощью функции customMenu вместо того, что было раньше:

$("#tree").jstree({plugins: ["contextmenu"], contextmenu: {items: customMenu}});
//                                                                    ^
// ___________________________________________________________________|

Изменить: Если вы не хотите, чтобы меню было воссоздано при каждом щелчке правой кнопкой мыши, вы можете поместить логику в обработчик действий для самого элемента меню удаления.

"label": "Delete",
"action": function (obj) {
    if ($(this._get_node(obj)).hasClass("folder") return; // cancel action
}

Изменить снова:. Посмотрев исходный код jsTree, похоже, что контекстное меню создается заново при каждом его показе (см. функции show() и parse()), поэтому я не вижу проблемы с моим первым решением.

Однако мне нравится обозначение, которое вы предлагаете, с функцией как значение для _disabled. Потенциальный путь для изучения состоит в том, чтобы обернуть свою функцию parse() своей собственной, которая оценивает функцию в disabled: function () {...} и сохраняет результат в _disabled, перед вызовом оригинала parse().

Не составит труда изменить исходный код напрямую. Строка 2867 версии 1.0-rc1 является релевантной:

str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";

Вы можете просто добавить строку до этого, которая проверяет $.isFunction(val._disabled), и если да, val._disabled = val._disabled(). Затем отправьте его создателям в виде патча:)

Ответ 2

Реализовано с различными типами node:

$('#jstree').jstree({
    'contextmenu' : {
        'items' : customMenu
    },
    'plugins' : ['contextmenu', 'types'],
    'types' : {
        '#' : { /* options */ },
        'level_1' : { /* options */ },
        'level_2' : { /* options */ }
        // etc...
    }
});

И функция customMenu:

function customMenu(node)
{
    var items = {
        'item1' : {
            'label' : 'item1',
            'action' : function () { /* action */ }
        },
        'item2' : {
            'label' : 'item2',
            'action' : function () { /* action */ }
        }
    }

    if (node.type === 'level_1') {
        delete items.item2;
    } else if (node.type === 'level_2') {
        delete items.item1;
    }

    return items;
}

Прекрасно работает.

Ответ 3

Очистить все.

Вместо этого:

$("#xxx").jstree({
    'plugins' : 'contextmenu',
    'contextmenu' : {
        'items' : { ... bla bla bla ...}
    }
});

Используйте это:

$("#xxx").jstree({
    'plugins' : 'contextmenu',
    'contextmenu' : {
        'items' : customMenu
    }
});

Ответ 4

Я адаптировал предложенное решение для работы с типами несколько иначе, возможно, это может помочь кому-то еще:

Где # {$ id_arr [$ k]} - ссылка на контейнер div... в моем случае я использую много деревьев, поэтому весь этот код будет выводить в браузер, но вы получаете идею. В принципе Я хочу все параметры контекстного меню, но только "Создать" и "Вставить" на Диске node. Очевидно, с правильными привязками к этим операциям позже:

<div id="$id_arr[$k]" class="jstree_container"></div>
</div>
</li>
<!-- JavaScript neccessary for this tree : {$value} -->
<script type="text/javascript" >
jQuery.noConflict();
jQuery(function ($) {
// This is for the context menu to bind with operations on the right clicked node
function customMenu(node) {
    // The default set of all items
    var control;
    var items = {
        createItem: {
            label: "Create",
            action: function (node) { return { createItem: this.create(node) }; }
        },
        renameItem: {
            label: "Rename",
            action: function (node) { return { renameItem: this.rename(node) }; }
        },
        deleteItem: {
            label: "Delete",
            action: function (node) { return { deleteItem: this.remove(node) }; },
            "separator_after": true
        },
        copyItem: {
            label: "Copy",
            action: function (node) { $(node).addClass("copy"); return { copyItem: this.copy(node) }; }
        },
        cutItem: {
            label: "Cut",
            action: function (node) { $(node).addClass("cut"); return { cutItem: this.cut(node) }; }
        },
        pasteItem: {
            label: "Paste",
            action: function (node) { $(node).addClass("paste"); return { pasteItem: this.paste(node) }; }
        }
    };

    // We go over all the selected items as the context menu only takes action on the one that is right clicked
    $.jstree._reference("#{$id_arr[$k]}").get_selected(false, true).each(function (index, element) {
        if ($(element).attr("id") != $(node).attr("id")) {
            // Let deselect all nodes that are unrelated to the context menu -- selected but are not the one right clicked
            $("#{$id_arr[$k]}").jstree("deselect_node", '#' + $(element).attr("id"));
        }
    });

    //if any previous click has the class for copy or cut
    $("#{$id_arr[$k]}").find("li").each(function (index, element) {
        if ($(element) != $(node)) {
            if ($(element).hasClass("copy") || $(element).hasClass("cut")) control = 1;
        }
        else if ($(node).hasClass("cut") || $(node).hasClass("copy")) {
            control = 0;
        }
    });

    //only remove the class for cut or copy if the current operation is to paste
    if ($(node).hasClass("paste")) {
        control = 0;
        // Let loop through all elements and try to find if the paste operation was done already
        $("#{$id_arr[$k]}").find("li").each(function (index, element) {
            if ($(element).hasClass("copy")) $(this).removeClass("copy");
            if ($(element).hasClass("cut")) $(this).removeClass("cut");
            if ($(element).hasClass("paste")) $(this).removeClass("paste");
        });
    }
    switch (control) {
        //Remove the paste item from the context menu
        case 0:
            switch ($(node).attr("rel")) {
                case "drive":
                    delete items.renameItem;
                    delete items.deleteItem;
                    delete items.cutItem;
                    delete items.copyItem;
                    delete items.pasteItem;
                    break;
                case "default":
                    delete items.pasteItem;
                    break;
            }
            break;
            //Remove the paste item from the context menu only on the node that has either copy or cut added class
        case 1:
            if ($(node).hasClass("cut") || $(node).hasClass("copy")) {
                switch ($(node).attr("rel")) {
                    case "drive":
                        delete items.renameItem;
                        delete items.deleteItem;
                        delete items.cutItem;
                        delete items.copyItem;
                        delete items.pasteItem;
                        break;
                    case "default":
                        delete items.pasteItem;
                        break;
                }
            }
            else //Re-enable it on the clicked node that does not have the cut or copy class
            {
                switch ($(node).attr("rel")) {
                    case "drive":
                        delete items.renameItem;
                        delete items.deleteItem;
                        delete items.cutItem;
                        delete items.copyItem;
                        break;
                }
            }
            break;

            //initial state don't show the paste option on any node
        default: switch ($(node).attr("rel")) {
            case "drive":
                delete items.renameItem;
                delete items.deleteItem;
                delete items.cutItem;
                delete items.copyItem;
                delete items.pasteItem;
                break;
            case "default":
                delete items.pasteItem;
                break;
        }
            break;
    }
    return items;
$("#{$id_arr[$k]}").jstree({
  // List of active plugins used
  "plugins" : [ "themes","json_data", "ui", "crrm" , "hotkeys" , "types" , "dnd", "contextmenu"],
  "contextmenu" : { "items" : customMenu  , "select_node": true},

Ответ 5

Вы можете изменить код @Box9 в соответствии с требованиями динамического отключения контекстного меню:

function customMenu(node) {

  ............
  ................
   // Disable  the "delete" menu item  
   // Original // delete items.deleteItem; 
   if ( node[0].attributes.yyz.value == 'notdelete'  ) {


       items.deleteItem._disabled = true;
    }   

}  

Вам нужно добавить один атрибут "xyz" в данные вашего XML или JSOn

Ответ 6

по состоянию на jsTree 3.0.9 Мне нужно было использовать что-то вроде

var currentNode = treeElem.jstree('get_node', node, true);
if (currentNode.hasClass("folder")) {
    // Delete the "delete" menu item
    delete items.deleteItem;
}

поскольку объект node, который предоставляется, не является объектом jQuery.