简体   繁体   中英

How can I parse gridstack.js items?

Maybe this is quite simple, but I'm still learning JS and stuff. I'm using the plugin https://github.com/troolee/gridstack.js and want to send ajax requests whenever a widget gets repositioned/resized. I wrote this (according to the official readme):

var serialize_widget_map = function (items) {
        console.log(items);
    };

    // onchange position/size
    $('.grid-stack').on('change', function (e, items) {
        console.log(items);
    });

Just to see what the console says: [Object, Object] - maybe because I have 2 widgets on page, but I have to notice that this quantity may vary (widgets might be removed/added dynamically).

How can I "parse" this "items" thing so I can access properties of the widgets?

Just in case someone's looking for the answer to this question, I have solved this problem:

$('.grid-stack').on('change', function (e, items) {
    var widgets = [];

    for (i = 0; i < items.length; i++) {
        var widgetsObj = {
            'widgetId': items[i].el.context.id,
            'x': items[i].x,
            'y': items[i].y,
            'width': items[i].width,
            'height': items[i].height
        }
        widgets.push(widgetsObj);
    }
}

Because the items variable may contain multiple objects, I loop through it to create a single array of objects with properties I need.

i came to your question because i was looking for a way to retrieve the current items / nodes

i found this solution, where an event is not required

grid = $('.grid-stack').data('gridstack');
items = grid.grid.nodes;
var serialize_widget_map = function (items) {
    console.log(items);
};

$('.grid-stack').on('change', function (e, items) {
    var widgets = [];

    for (var i = 0; i < items.length; i++) {
        var widgetsObj = {
            'widgetId': items[i],
            'x': items[i].x,
            'y': items[i].y,
            'width': items[i].width,
            'height': items[i].height
        }
    }
    serialize_widget_map(widgetsObj);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM