edit an array in metawidget

741 views Asked by At

I am using metawidget from javascript.
My Json object contains an array:
{"db_host" : ["1054.iil", "070.iil", "1031.iil"]}

When displaying it with metawidget it is readonly with no options to edit/add/remove. Is it possible to change that?

2

There are 2 answers

0
Richard Kennard On BEST ANSWER
0
Richard Kennard On

Manipulating arrays is fraught with personal choices about UI design. For example: is deletion done by a right-click menu? Or a delete icon on the end of each row? Or at the start of each row? Is addition done using a blank row at the end of the table, or as a footer row? Etc etc.

Because of this, out-of-the-box Metawidget only goes so far. You should see it render the array as a table? This is done by metawidget.widgetbuilder.HtmlWidgetBuilder.

For custom use cases, you can create your own WidgetBuilder and chain it together with the original ones using CompositeWidgetBuilder. Then your own WidgetBuilder can handle special cases (like arrays) and 'fall back' to the original WidgetBuilders for everything else.

As a shortcut, the existing HtmlWidgetBuilder also has some methods you can override like 'createTable' and 'addColumn'. So, just roughly, something like the below. It'll remove a row when you click on it.

var _myWidgetBuilder = new metawidget.widgetbuilder.HtmlWidgetBuilder();
var _superAddColumn = _myWidgetBuilder.addColumn;
_myWidgetBuilder.addColumn = function( tr, value, attributes, mw ) {

    var td = _superAddColumn( tr, value, attributes, mw );

    // Warp column contents with an anchor

    var anchor = document.createElement( 'a' );
    anchor.setAttribute( 'href', '#' );
    anchor.setAttribute( 'onclick', 'this.parentNode.parentNode.parentNode.removeChild( this.parentNode.parentNode )' );
anchor.innerHTML = td.innerHTML;
    td.innerHTML = '';
    td.appendChild( anchor );
};
var mw = new metawidget.Metawidget( document.getElementById( 'metawidget' ), {
    widgetBuilder: _myWidgetBuilder
} );
mw.toInspect = {
    firstname: 'Homer',
    surname: 'Simpson',
    age: 36,
    family: [ {
        firstname: 'Marge',
        surname: 'Simpson'
    }, {
        firstname: 'Bart',
        surname: 'Simpson'
    } ]
};