【问题标题】:KineticJS on event pass variable事件传递变量上的 KineticJS
【发布时间】:2013-08-14 11:04:44
【问题描述】:

在 jQuery 中,可以将其他变量传递给事件以处理范围问题,如下所示:

$('#element').click({index: i}, function(event){
    console.log(event.data.index);
});

如何在 KineticJS 中执行此操作,因为 on 事件方法不提供此功能?我设法使用数组生成了圆圈,但似乎无法将特定数据传递给每个事件:

var data = [12.22, 34.45, 8.9];
var circles = [];

for(var i in data){
circles[i] = new Kinetic.Circle({
    x : Math.random() * stage.getWidth(),
    y : Math.random() * stage.getHeight(),
    radius : 4,
    fill : 'white'
});

circles[i].on('mousemove', {value: data[i]}, function() {
    console.log('need to use value for this particular event here');
});

shapesLayer.add(circles[i]);
}

【问题讨论】:

    标签: events canvas kineticjs


    【解决方案1】:

    你可以给circle添加一个新的属性,并像这样在里面保存数据值:

    circles[i].setAttr('dataVal',data[i]);

    然后您可以像这样在事件处理程序中访问它。

    circles[i].on('mousemove', function() {
        console.log(this.getAttr(`dataVal`));
    });
    

    【讨论】:

    • 很好的答案 Ani,非常有帮助。感谢您发帖。
    【解决方案2】:

    感谢@Ani。当我发布这个问题时,我开始思考我可能只是将一个属性“注入”到对象中并像这样访问它。从编码标准来看,您的方式更好,但即使其粗糙,以下内容也适用:

    circles[i].value = data[i];
    
    circles[i].on('mouseover', function() {
        console.log(this.value);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2010-10-09
      • 2021-07-11
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多