famo.Us /js:绑定动态数据,点击事件发送数据

famo.us/js: bind dynamic data to click event for emitting data

本文关键字:数据 事件 动态 Us js 绑定 famo      更新时间:2023-09-26

我想将点击事件绑定到我在数组中收集的表面。每次咔哒声响起,我都想发出一条信息。但每次点击都应该发出自己的数据。我知道我的范围有问题,但我不知道如何解决它:(

for(var i=0; i < clickableSurfaces.length; i++) {
    clickableSurfaces[i].on('click', function() {
       // output: undefined
       console.log(this.options[i]);
            
       // output: desired data
       console.log(this.options[0]);
       
        // emit data another view
       this._eventOutput.emit('foo', {data: this.options[i]});
    }.bind(this));
}

不知何故,我必须让i变量在.on(...)内部工作,但绑定它(.bind(this, i))不起作用。有人知道怎么解决这个问题吗或者能给我指出正确的方向吗?

在设置侦听器时绑定数据可能更容易。这样你就不用担心传递的对象的索引值了。

for(var i=0; i < clickableSurfaces.length; i++) {
    clickableSurfaces[i].on('click', function(data, event) {
        // data = this.options[i]
        console.log(data);
        // emit data to another view
        // this = anotherView in this case
        this._eventOutput.emit('foo', {data: data});
    }.bind(anotherView, this.options[i]));
}
anotherView.on('foo', function(event) {
    // event.data was emitted with the event
    console.log(event.data);
});

找到了解决方案:您不仅必须将"i"绑定到事件,还必须将参数"i"分配给函数。

完整代码:

for(var i=0; i < clickableSurfaces.length; i++) {
clickableSurfaces[i].on('click', function(**i**) {
   // output: undefined
   console.log(this.options[i]);
   // output: desired data
   console.log(this.options[0]);
    // emit data another view
   this._eventOutput.emit('foo', {data: this.options[i]});
}.bind(this, **i**));
}