In my Vue mounted code, I am calling a function test via this.test(). This works fine as intended.
When however I am calling this.test() from the new ResizeObserver function, I am getting an error
this.test is not a function
I understand that this is because the this there is now pointing to the resizeObserver. What I do not understand is what I should use there instead. Removing the this also gives an error.
I have the following Vue code
mounted: function() {
this.test();
new ResizeObserver(function() {
this.test();
}).observe(this.g("tC"));
},
methods: {
test: function() {}
....
}
Advertisement
Answer
You should either bind “this” to the function passed to ResizeObserver
mounted: function() {
this.test();
new ResizeObserver(function() {
this.test();
}.bind(this)).observe(this.g("tC"));
},
Or use an arrow function (if your environment supports ES6) since arrow functions use “this” value of the outer scope:
mounted: function() {
this.test();
new ResizeObserver(() => {
this.test();
}).observe(this.g("tC"));
},