ducksboard / gridster.js

gridster.js is a jQuery plugin that makes building intuitive draggable layouts from elements spanning multiple columns
http://gridster.net/
MIT License
6.03k stars 1.2k forks source link

Reinitialize gridster after adding new grid to DOM #205

Closed ghost closed 11 years ago

ghost commented 11 years ago

We're building a paginated dashboard application wherein widgets can be dragged and reordered -- works great!

However, the user can create additional dashboards on the fly without reloading the page. New dashboard containers (Gridster grids...) are added to the DOM when the user clicks a button. The problem is Gridster hasn't been initialized on the newly added grid, so neither preloading the grid with widgets or dynamically adding a widget works, i.e., "Uncaught TypeError: Cannot call method 'add_widget' of undefined"

What is the best method of applying gridster to a dynamically added element? I haven't had any luck playing with variations of this:

var gridsterSettings = {
    widget_margins: [10, 10],
    widget_base_dimensions: [295, 298],
    max_size_x: 3,
    max_size_y: 12,
    min_cols: 3,
    serialize_params: function ($w, wgd) {
        return {
            type: $w.context.dataset.type,
            col: wgd.col,
            row: wgd.row,
            size_x: wgd.size_x,
            size_y: wgd.size_y
        }
    }
}
var gridster = $("ul.dashboard").gridster(gridsterSettings);

$("#Configure .settingsMenu a").click(function () {
    var dashboardMarkup = '<div><ul class="dashboard"></ul></div>';
    $('#dashboards').cycle('add', dashboardMarkup);
    $("ul.dashboard").gridster(gridsterSettings);
}

Thank you in advance for any help.

ghost commented 11 years ago

The solution I settled on was to watch the container that holds the various dashboards and apply gridster to any new elements:

$('#dashboards').on("DOMNodeInserted", function (event) {
    if (event.target.parentNode.id == 'dashboards') {
        $(event.target).children("ul.dashboard").gridster(gridsterSettings);
    };
});

It appears DOM mutation events have been deprecated (but this appears to work fine in the browser's we are supporting.)