Tuesday, September 16, 2014

jQuery "events-map" with jsTree or any jQuery object

I've been working with jsTree recently. It is an excellent jQuery plugin with great support from its developer Ivan Bozhanov. You can check out the jsTree site to learn all about it but I will just be using it for my example jQuery object instance here.

jsTree has several built-in and plugin events. In my case, I needed to make AJAX calls to WCF REST methods to update a back-end file system. So, I needed to attach event handlers to their corresponding events. 2 of the events were move_node and rename_node. The recommended way to attach was with jQuery's .on() method.

With just one event, you're fine just doing this:

 $('#jstree').on("move_node.jstree", function (e, data) {  
         $.get("/Main.svc/json/move/", {node_id: data.node.id, target_node_id: data.parent});  
         console.log(data.node.id + " moved");  
       }).jstree({...  

But, with multiple events, the cleanest way IMHO is to use the "events-map" syntax:

 $('#jstree').on({  
         "move_node.jstree": function (e, data) {  
           $.get("/Main.svc/json/move/", {node_id: data.node.id, target_node_id: data.parent});  
           console.log(data.node.id + " moved");  
         },  
         "rename_node.jstree": function (e, data) {  
           $.get("/Main.svc/json/update/", {node_id: data.node.id, text: data.node.text});  
           console.log(data.node.id + " renamed");  
         }  
       }  
     ).jstree({...

You can do this with bind() as well but since jQuery is moving away from bind() and recommending on(), we should do that.

No comments:

Post a Comment