问题描述
在尝试构建网格堆栈破折号时遇到问题
Running into a problem with my attempt to build a gridstack dash
当尝试加载页面时,我收到未捕获的TypeError:无法读取未定义的属性'addWidget'."(代码基于基本的GridStack序列化演示 https://github.com/gridstack/gridstack.js/blob/develop/demo/serialization.html )
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)
我更改的脚本部分是
<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
最好的解决方法是这个.输入getJSON时网格消失
Best I can work out is this.grid disappears as I enter getJSON
数据可以很好地加载BTW,我看到 items
填充了我期望的数据.
Data loads fine BTW, I see items
populated with the data I expect.
推荐答案
在 loadGrid
方法中,此上下文似乎不正确,请尝试将其更改为:
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);
如果您使用的上下文不正确,则 this
会引用这些嵌套函数中的其他内容,可能是 $
或 _
If you don't use the proper context, this
will refer to something else inside those nested functions, either $
or _
possibly.
这篇关于无法使用JSON和gridstack读取未定义的属性addWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!