Jstree show context menu conditionally

Jstree show context menu conditionally

The code below shows my attempt to show a jstree context menu only at level 1.

The menu shows at level one and the options work which is what I want.

The menu does not show at level 2 which is what I want.

But, after selecting a level 2 node, then selecting a level 1 node the menu options appear but do not 'fire'.

Any help appreciated

Fiddle: https://jsfiddle.net/NervousElk/4p5hqg0r/17/ 

document.getElementById("gobtn").addEventListener("click", buildtree);


function buildtree()

{         

$('#ttstafftree').jstree(

{

plugins: ["wholerow",  "json_data", "ui", "themes", "sort", "state",  "contextmenu"], //"checkbox",

'core' : 

{

"check_callback": true,

'data' : 

    [

{ "id" : "ajson1", "parent" : "#", "text" : "Root 1" },

{ "id" : "ajson1-1", "parent" : "ajson1", "text" : "a" },

{ "id" : "ajson2", "parent" : "#", "text" : "Root 2" },

{ "id" : "ajson2-1", "parent" : "ajson2", "text" : "b" },

]

},

                               

"contextmenu": 

{                           

    "items": 

{

                      opt1: 

  {

                        label: "opt 1",

                        action: function(data) 

    {

alert('opt 1')  

                        }

                      },

  

  opt2: 

  {

                        label: "opt 2",

                        action: function(data) 

    {

alert('opt 2')  

                        }

                      }         

                    }   

                },

})  

            .on('show_contextmenu.jstree', function(e, reference, element) 

{                           

      if ( reference.node.parents.length != 1) 

    {                    

   $('.vakata-context').remove();                   

                }


            });   

}