Can i apply JSON to current gridster list?

171 Views Asked by At

I have a list of already generated data I get from server. (I have some widgets generated inside li)

<div class='gridster'>
<ul>
<li>data item 1</li>
<li>data item 2</li>
<li>data item 3</li>
</ul>
</div>

My JSON for example:

[{"col":1,"row":1,"size_x":3,"size_y":2},{"col":4,"row":1,"size_x":3,"size_y":2},{"col":1,"row":3,"size_x":6,"size_y":2}]

In gridster demo we use this code to apply size and position from JSON

$('.js-seralize').on('click', function () {
    gridster.remove_all_widgets();
    $.each(serialization, function () {
        gridster.add_widget('<li />', this.size_x, this.size_y, this.col, this.row);
    });
});

In this case we use gridster.remove_all_widgets(); and this is a problem for me, I need to save my data items somewhere and after output them back.

What is the best solution to apply JSON to current list, without using remove_all_widgets() function?

UPD: I generate my list from asp mvc app and i want to add size and position to list on client side. For me it looks like: $('gridster ul').apply(jsonString);

1

There are 1 best solutions below

0
Alexander Groshev On BEST ANSWER

To apply JSON to the list that already exist i've used this code:

 var CurrentGridState = `[{"col":1,"row":3,"size_x":3,"size_y":2},{"col":4,"row":3,"size_x":3,"size_y":2},{"col":1,"row":1,"size_x":6,"size_y":2}]`;


 $(function () { //DOM Ready
        var json = JSON.parse(CurrentGridState);
        $.each($('.gridster ul li'), function (item, value) {
            console.log(json[item]['col']);
            $(value).attr("data-col",json[item]['col']);
            $(value).attr("data-row",json[item]['row']);
            $(value).attr("data-sizex",json[item]['size_x']);
            $(value).attr("data-sizey",json[item]['size_y']);
        });

    $(window).trigger('resize');
       gridster =  $(".gridster ul").gridster({
            widget_margins: [10, 10],
           widget_base_dimensions: [140, 140],
           max_cols: 10,
           max_rows: 25,
            draggable: {
                stop: function (e, ui, $widget) {
                    //alert('drag!');
                }
            },
            resize: {
                stop: function (e, ui, $widget) {
                    $(window).trigger('resize');
                    serializeCurrentState();
                },
                enabled: true
            },
        }).data('gridster');
    });