6

I'm using the jsTree plugin to list folders in the file system. I need to prevent a user from changing to another node before a certain condition is met.
The below code does not stop the propagation... i saw some solutions with other plugins but this is a simple task it must be possible without other plugins.

$('#jstree').on('select_node.jstree', function (e) 
{
    if (!changeAllowed()
    {
        e.preventDefault(); 
        e.stopImmediatePropagation();
    }
}); 
Salmonela
  • 95
  • 1
  • 2
  • 11

1 Answers1

13

Documenting for myself and posterity: you need to include the following function AFTER loading the jstree JS (from: https://github.com/vakata/jstree/blob/master/src/misc.js):

// jstree conditional select node
(function ($, undefined) {
  "use strict";
  $.jstree.defaults.conditionalselect = function () { return true; };

  $.jstree.plugins.conditionalselect = function (options, parent) {
    // own function
    this.select_node = function (obj, supress_event, prevent_open) {
      if(this.settings.conditionalselect.call(this, this.get_node(obj))) {
        parent.select_node.call(this, obj, supress_event, prevent_open);
      }
    };
  };
})(jQuery);

Then when initializing an instance of jstree do something like this:

$('#jstree').jstree({
  'conditionalselect' : function (node) {
    return <something that determines condition> ? true : false;
  },
  'plugins' : ['conditionalselect'],
  'core' : {
    <core options>
  }
});
Joni
  • 831
  • 7
  • 23
  • 2
    This has a bug. Suppose the tree allows only 1 selection, and you select A, and then you select B, and the 'conditional' rejects B. You'd expect A to be still selected, but it isn't. – John Henckel Feb 25 '15 at 17:23