Thursday, April 19, 2012

"setXMLFromString" Extension for EditableGrid

EditableGrid is a very useful datagrid and chart component. It's written in JS, and after the usual short wrestling match/learning curve to incorporate into my projects, which these days are very data display heavy; lots of charts, tabular data that has to be interactive, I was pleased with the usage and display results.

You can find out more about EditableGrid here:

www.editablegrid.com

However, there is, from what I can see, one major API oversight, and forgive me if it's there but I looked in docs and source and couldn't find it: you can't set the xml from a string or dom object directly. You have to either fake a url call in the loadXML api call, or some other such hacky voodoo.

So I wrote a very simple extension for EditableGrid that allows you to do it straightforwardly.

Create a javascript file, call it, "useXMLString.js". Put it in the extensions directory of your EditableGrid structure.

Put this function in it.



EditableGrid.prototype.setXMLFromString = function ( theXMLString ) {

if ( window.DOMParser )
{
var parser = new DOMParser ( );
this.xmlDoc = parser.parseFromString ( theXMLString, "application/xml" );
}
else
{
this.xmlDoc = new ActiveXObject ( "Microsoft.XMLDOM" ); // IE
this.xmlDoc.async = "false";
this.xmlDoc.loadXML ( theXMLString );
}

this.processXML ( );
this.tableLoaded ( );
}



Not much to see; I add a function to the EditableGrid prototype, use typical "browsers or IE" DOM parsing to turn the string into a DOM object, set the xmlDoc object of EditableGrid to that DOM object, then run the processXML and tableLoaded functions. This is pretty much how the usual EditableGrid.loadXML function works (you can see it in the EditableGrid source), I'm just taking out the need to use a URL.

Save it, and add it to your imports, the way you'd add any other extension to a JS component.

Now, don't call myEditableGrid.loadXML ( url ). Substitute myEditableGrid.setXMLFromString ( theXMLString ).

That's it, works like a charm. Note that you are responsible for making sure your XML string is a valid object.

As always, thanks for visiting.

1 comment:

  1. Oh and btw this is a great study in writing JS extensions, which is actually very easy and powerful when you get it. Note that the component I'm extending is minified; I had a couple of people tell me, "you'll need to use the source then," which isn't true (why anybody would think so I don't know...you don't need the source of a library if you want to extend or override something).

    ReplyDelete