问题
Running into a problem with my attempt to build a gridstack dash
I get "Uncaught TypeError: Cannot read property 'addWidget' of undefined" when trying to load the page.. (the code is based on the basic gridstack serialized demo https://github.com/gridstack/gridstack.js/blob/develop/demo/serialization.html)
my changed script section is
<script type="text/javascript">
$(function() {
var options = {};
$('.grid-stack').gridstack(options);
new function() {
this.grid = $('.grid-stack').data('gridstack');
this.loadGrid = function() {
this.grid.removeAll();
debugger;
const URL = `//${window.location.hostname}/dashboard/getDashboard`;
$.getJSON(URL, function(items) {
_.each(items, function(node) {
this.grid.addWidget($('<div><div class="grid-stack-item-content" /></div>'),
node.x, node.y, node.width, node.height, true, 4, 12, 1, 8, node.id);
}.bind(this));
});
return false;
}.bind(this);
this.saveGrid = function() {
this.serializedData = _.map($('.grid-stack > .grid-stack-item:visible'), function(el) {
el = $(el);
var node = el.data('_gridstack_node');
return {
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
$('#saved-data').val(JSON.stringify(this.serializedData, null, ' '));
return false;
}.bind(this);
this.clearGrid = function() {
this.grid.removeAll();
return false;
}.bind(this);
$('#save-grid').click(this.saveGrid);
$('#load-grid').click(this.loadGrid);
$('#clear-grid').click(this.clearGrid);
this.loadGrid();
};
});
</script>
Any suggestions? I've tried a number of things, but keep getting dead ends
Best I can work out is this.grid disappears as I enter getJSON
Data loads fine BTW, I see items
populated with the data I expect.
回答1:
It seems like the context of this in the loadGrid
method may be incorrect, try changing it to this:
this.loadGrid = function () {
this.grid.removeAll();
debugger;
const URL = `//${window.location.hostname}/dashboard/getDashboard`;
const context = this;
$.getJSON(URL, function (items) {
_.each(items, function (node) {
context.grid.addWidget($('<div><div class="grid-stack-item-content" /></div>'),
node.x, node.y, node.width, node.height, true, 4, 12, 1, 8, node.id);
}.bind(this));
});
return false;
}.bind(this);
If you don't use the proper context, this
will refer to something else inside those nested functions, either $
or _
possibly.
来源:https://stackoverflow.com/questions/54287633/cant-read-property-addwidget-of-undefined-with-json-and-gridstack