Search code examples
javascriptevent-handlingdom-eventsbindfamo.us

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


I'd like to bind click events to surfaces which I collected in an array. Every time a click is fired, I'd like to emit a message. But every click should emit it's own data. I know I have a problem with the scope but I couldn't figure out how to solve it :(

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));
}

Somehow I have to get the i variable to work inside of .on(...) but binding it (.bind(this, i)) didn't work. Does anyone know how to solve it or could point me in the right direction?


Solution

  • It might be easier to bind the data when you setup the listener. This way you are not worried about the index value of the object passed.

    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);
    });