问题
Is it possible to bind context on method? I made an pixi graphic:
var square = new PIXI.Graphics();
Then I call my method this.onDragMove
and bind square
.
square
.on('pointermove', this.onDragMove.bind(square));
But when I log this
it still logs the vue component.
onDragMove() {
console.log(this);
console.log('Object is moving')
},
Am I doing something wrong or is it just not possible?
回答1:
According to the docs:
All methods will have their
this
context automatically bound to the Vue instance.
You cannot rebind the this
context of methods defined on a Vue instance, for the same reason that the following code does not work as expected:
function foo() {
return this;
}
const X = {};
const Y = {};
const fooX = foo.bind(X);
const fooY = fooX.bind(Y); // Attempting to bind an already bound function
console.log(fooX() === X); // true
console.log(fooY() === X); // true
console.log(fooY() === Y); // false
You can access the original unbound function through $options:
square
.on('pointermove', this.$options.methods.onDragMove.bind(square));
来源:https://stackoverflow.com/questions/51168564/bind-context-on-vue-js-method-with-pixi-js