jstree.sort.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * ### Sort plugin
  3. *
  4. * Automatically sorts all siblings in the tree according to a sorting function.
  5. */
  6. /*globals jQuery, define, exports, require */
  7. (function (factory) {
  8. "use strict";
  9. if (typeof define === 'function' && define.amd) {
  10. define('jstree.sort', ['jquery','jstree'], factory);
  11. }
  12. else if(typeof exports === 'object') {
  13. factory(require('jquery'), require('jstree'));
  14. }
  15. else {
  16. factory(jQuery, jQuery.jstree);
  17. }
  18. }(function ($, jstree, undefined) {
  19. "use strict";
  20. if($.jstree.plugins.sort) { return; }
  21. /**
  22. * the settings function used to sort the nodes.
  23. * It is executed in the tree's context, accepts two nodes as arguments and should return `1` or `-1`.
  24. * @name $.jstree.defaults.sort
  25. * @plugin sort
  26. */
  27. $.jstree.defaults.sort = function (a, b) {
  28. //return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : this.get_type(a) >= this.get_type(b);
  29. return this.get_text(a) > this.get_text(b) ? 1 : -1;
  30. };
  31. $.jstree.plugins.sort = function (options, parent) {
  32. this.bind = function () {
  33. parent.bind.call(this);
  34. this.element
  35. .on("model.jstree", $.proxy(function (e, data) {
  36. this.sort(data.parent, true);
  37. }, this))
  38. .on("rename_node.jstree create_node.jstree", $.proxy(function (e, data) {
  39. this.sort(data.parent || data.node.parent, false);
  40. this.redraw_node(data.parent || data.node.parent, true);
  41. }, this))
  42. .on("move_node.jstree copy_node.jstree", $.proxy(function (e, data) {
  43. this.sort(data.parent, false);
  44. this.redraw_node(data.parent, true);
  45. }, this));
  46. };
  47. /**
  48. * used to sort a node's children
  49. * @private
  50. * @name sort(obj [, deep])
  51. * @param {mixed} obj the node
  52. * @param {Boolean} deep if set to `true` nodes are sorted recursively.
  53. * @plugin sort
  54. * @trigger search.jstree
  55. */
  56. this.sort = function (obj, deep) {
  57. var i, j;
  58. obj = this.get_node(obj);
  59. if(obj && obj.children && obj.children.length) {
  60. obj.children.sort($.proxy(this.settings.sort, this));
  61. if(deep) {
  62. for(i = 0, j = obj.children_d.length; i < j; i++) {
  63. this.sort(obj.children_d[i], false);
  64. }
  65. }
  66. }
  67. };
  68. };
  69. // include the sort plugin by default
  70. // $.jstree.defaults.plugins.push("sort");
  71. }));