jsTree: async loading

LeftyX picture LeftyX · Mar 11, 2010 · Viewed 12.4k times · Source

I am trying to use this jQuery plugin (jsTree) in one of my project.
All the others I've found haven't been recently updated.
Anyway, I am using this plugin to load a folder structure, but I would like to do this operation async. The examples I've found on their site (called async) are ridiculous. I've tried to check on the Internet but it seems that most people load the whole tree. I would like to load a branch on every single node click. I am using JSON.

Thank in advance

Answer

Nick Craver picture Nick Craver · Mar 11, 2010

I'm using this with jsTree in jQuery 1.4 at the moment, here's an example, it's very uncompressed to make it a bit clearer:

$("#QuickNav").tree({
  data: {
    async: true,
    type: "json",
    opts: {
      method: "POST",
      url: rootPath + "QuickNav"
    }
  },
  callback: {
    beforedata: function(NODE, TREE_OBJ) {
      return $(NODE).attr("id") === "" ?
       { id: $(NODE).find("a:first").attr("id")} :
       { id: $(NODE).attr("id") || 0 };
    },
    onchange: function(NODE) {
      document.location.href = $(NODE).children("a:first").attr("href");
    }
  }
});

A sample of JSON I'm returning from that Url:

[{
    "data": {
        "title": "Title (<b link='/Thing/200' class='gtp'>Go to Page</b>)",
        "attributes": {
            "href": "#",
            "id": "200"
        }
    },
    "state": "closed"
}]

The id there is the only thing that gets passed to my web service method callbacks, resulting in JSON like this being returned:

[{
    "data": {
        "title": "Sites",
        "attributes": {
            "href": "#",
            "class": "TreeTitle"
        }
    },
    "state": "open",
    "children": [
        {
            "data": {
                "title": "00001 - Test Thing",
                "type": "link",
                "attributes": {
                    "href": "/Site/39063",
                    "class": "TL"
                }
            }
        },
        {
            "data": {
                "title": "00002 - Test Thing 2",
                "type": "link",
                "attributes": {
                    "href": "/Site/39069",
                    "class": "TL"
                }
            }
        }
    ]
}]