简体   繁体   English

KineticJS向数组中保存的对象添加事件

[英]KineticJS Adding Events to Objects held in an Array

for (var x = 0; x < 10; x++) {
            //var xx = x;
            for (var y = 0; y < 10; y++) {
                //var yy = y;
                displayboxs[x][y][1].on('click', function() {
                    displayboxs[x][y][0] = 'P';
                });
            }
        }

so this is the code i want to run however the displaboxs[x][y][0] = 'P'; 所以这是我要运行的代码,但是displaboxs [x] [y] [0] ='P'; part gives an error. 部分给出了错误。 I found that trying to change any array the way I am trying to doesn't work, unfortunately however this is the only way I can do it unless I add each event manually (i'd rather not). 我发现尝试以我尝试的方式更改任何数组都行不通,但是不幸的是,这是我可以做到的唯一方法,除非我手动添加每个事件(我宁愿不这样做)。 I also found that by storing the x and y variables in another i can prevent the error (the portions of the code that are commented out shows this) however i get strange results. 我还发现通过将x和y变量存储在另一个变量中,我可以防止错误(注释掉的代码部分显示了此错误),但是我得到了奇怪的结果。 For example if I print the area of the array that was changed RIGHT after it was changed it will be 'P' however after i have changed many locations on the array to 'P' and print the whole array all the elements will still be set to default exept the last spot in the array which will be 'P'. 例如,如果我在更改后打印右更改的数组区域,它将是“ P”,但是在将数组上的许多位置更改为“ P”并打印整个数组后,所有元素仍将被设置默认显示数组中的最后一个点为“ P”。 Weird right? 对吗? All suggestions are appreciated!!! 所有建议表示赞赏!!! Thanks for reading guys. 感谢您的阅读。

One problem is that x,y are long out-of-scope when any click is fired. 一个问题是,当触发任何单击时,x,y会超出范围。

Refactor by giving each displayboxs[x][y][1] a reference to the displayboxs[x][y][0] that it should alter when clicked. 通过为每个显示框[x] [y] [1]提供对显示框[x] [y] [0]的引用,以使其在单击时发生变化来进行重构。

Something like this (warning...untested code!): 像这样(警告...未经调试的代码!):

for (var x = 0; x < 10; x++) {
    for (var y = 0; y < 10; y++) {
        displayboxs[x][y][1].on('click', function() {
            this.myZero = 'P';
        });
        (displayboxs[x][y][1]).myZero=displayboxs[x][y][0];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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