El Dude
El Dude

Reputation: 5618

JS / TS must use bind but still need original this

I am not sure how to approach this user interaction problem I have. API is 3DMol

I am trying to access both this elements in

model.setClickable({chain: theChain, resi: mappedPosition}, true, function(){
    console.log(this);
});

First of all, for the original implementation as above this would be a location the user clicked on. However, I as well need to combine the clicked location with some value from the calling object outside.

I tried .bind(null,this) yet within the function this is set to null.

I tried a closure

const clickClosure = function(){

    const mutations = self.alignment.mutations;

    function clicker(){
        console.log(this);
        console.log(mutations);
    }

    return clicker();
} 

model.setClickable({chain: theChain, resi: mappedPosition}, true,clickClosure);

to find that mutations existed, but this was not defined. Any idea how to get both without using global variables?

Upvotes: 1

Views: 71

Answers (1)

joh04667
joh04667

Reputation: 7427

Use a lambda function to pass down a lexical this.

model.setClickable({chain: theChain, resi: mappedPosition}, true, (stuff) => {
    console.log(this, stuff); // no `this` binding to the function
});

That should keep this bound to the caller, and it's really the only way to get that reference from a callback like this.

Upvotes: 1

Related Questions