// Ajax Tree View // Written by Daniel Mendler, 2009 (function($) { // Create treeview // $('div#id').treeView(...); $.fn.treeView = function(options) { if (!options) { options = {}; } if (!options.root) { options.root = '/'; } if (!options.url) { options.url = '/treeview.json'; } if (!options.delay) { options.delay = 2000; } if (!options.ajax) { options.ajax = function(path, success, error) { $.ajax({url: options.url, data: { dir: path }, success: success, error: error, dataType: 'json'}); }; } // Store if node is expanded function setExpanded(path, expanded) { if (options.stateStore) { var state = $.storage.get(options.stateStore, []); if (!expanded) { state = $.grep(state, function(n, i) { return n != path; }); } else if ($.inArray(path, state) < 0) { state.push(path); } $.storage.set(options.stateStore, state); } } // Check if node is expanded function isExpanded(path) { return options.stateStore && $.inArray(path, $.storage.get(options.stateStore, [])) >= 0; } // Create child element. // Data is array: [has-children, classes, path, name] function createChild(data) { var path = data[2], child = $('
  • '), hitarea = child.children('.hitarea'); child.data('name', data[3]); hitarea.click(function() { if (hitarea.hasClass('collapsed')) { openTree(child, path); hitarea.removeClass('collapsed').addClass('expanded'); } else { child.children('ul').hide(); hitarea.removeClass('expanded').addClass('collapsed'); } setExpanded(path, hitarea.hasClass('expanded')); return false; }); if (isExpanded(path)) { openTree(child, path); hitarea.removeClass('collapsed').addClass('expanded'); } return child; } // Open tree element with path function openTree(element, path) { // Cache key for cached json data var cacheKey = options.cacheStore ? options.cacheStore + ':' + path : null; // Store json in cache function store(data) { if (cacheKey) { $.storage.set(cacheKey, data); } } // Data loaded via ajax (callback) or from the cache function dataLoaded(data) { var ul = $('