Link 'this' from two different contexts

0

I am creating a prototype with its event listeners and their respective handlers.

The issue is that I need two 'this' in the same handler:

this._items = $(".playlist-item");
//...
this._items.click( this.itemClickedHandler( ?? ) );

In other handlers where only the instance was needed this used the bind method:

this._player.on('ended', this.videoEndedHandler.bind(this))

At the moment I left the code, so that at least it worked, like this:

var that = this;
this._items.click(function(){
   var index = $(this).data("slick-index");
   that.jumpTo(index);
});
    
asked by Miguel González 11.03.2017 в 04:16
source

1 answer

1
  

The issue is that I need two 'this' in the same handler:

You can not, there is only one variable and you can not have two values at the same time: / And it does not make sense that you do it that way since if this were this and that at the same time, how does the compiler know then what do you mean? Also if you could use this in this way I think it would be quite confusing to read the program.

The current approach is correct, but I think the variable that should be called differently so that explicitly understand what piece is involved. For example: var moduloPadre (ok, it's not such a good example)

Anegodic note: it is possible to make a mix of both objects and bindearlo, but that would be even worse to read and more difficult to maintain and of course, there can be 2 members with the same name because one would step on the other, ex:

var este = { var1: 'valor1', var2: 'valor2' }; 
var aquel = { var2: 'valor3', var3: 'valor4' };

// haces la mezcla de objetos
var mezcla = Object.assign(este, aquel);

// preparas la funcion bindeada a la mezcla
var bindeada = function() {
   console.log( this );
}.bind( mezcla );

// esta la invocaria el callback 
bindeada();
    
answered by 11.03.2017 / 04:34
source