Howto not shoot yourself in the foot when trying to fire Ajax calls when clicking on a nodeAfter a lengthy talk to Bernard on freenode (thanks, man), we've come up with the following solution to tackle the issue of not being able to define your own a tag in the text property of a node (of course, that would work too - but it would leave you standing in the cold when trying to change the text of the node - I have experienced a rather weird behaviour where text assigned with the setText method would end up getting prepended to the current text: not desirable).
Note that this example is based on the wonderful work of Nick released in the Forum [1].
I'm using this code in Rails, so the Ajax call is made using Prototype.
Ext.onReady(function(){ tree = new Ext.tree.TreePanel('users', { animate:true, enableDD:false, loader: new Ext.tree.TreeLoader(), // Note: no dataurl, register a TreeLoader to make use of createNode() lines: true, selModel: new Ext.tree.MultiSelectionModel(), containerScroll: false }); var users_json = [{ onclick: "new Ajax.Request('http://domain/users/1.js', {asynchronous:true, evalScripts:true, method:'get'}); false;", cls: "file", text: "Forename Surname", id: "user_1", leaf: true }]; // set the root node var root = new Ext.tree.AsyncTreeNode({ text: 'Users', draggable:false, id:'source', children: users_json }); tree.setRootNode(root); tree.on('click', function(n){ if(n.isLeaf() && n.attributes.onclick){ eval(n.attributes.onclick); } }); tree.render(); root.expand(); });
Notice that onclick is a custom node attribute that gets read in the on click function that's defined on the tree. Should the node be a leaf and have the onclick attribute set, the code in the onclick gets eval'd and the Ajax request is sent - just like it would if you'd click on a normal link that had the Ajax request set in an onclick.