inteja Posted February 21, 2017 Share Posted February 21, 2017 I'm still a relative newbie with BJS and typescript. I've managed to get observers working in my TS class but I found that I couldn't use "this" instance references within the callback function e.g. class MyMesh extends BABYLON.Mesh { private myMeshChild:BABYLON.Mesh; constructor() { // Create child mesh and add some animation etc. this.myMeshChild.onBeforeRenderObservable.add(function () { console.log(this.myMeshChild.rotation); } } } This compiles fine but results in runtime error "Cannot read property 'rotation' of 'undefined'". But if I instead assign to a local variable first, then it works, e.g. class MyMesh extends BABYLON.Mesh { private myMeshChild:BABYLON.Mesh; constructor() { // Create child mesh and add some animation etc. let myMeshChild = this.myMeshChild; this.myMeshChild.onBeforeRenderObservable.add(function () { console.log(myMeshChild.rotation); } } } I feel like I'm using Observables all wrong in Typescript. I'm wondering what's the best way to pass variables to the callback function from within my TS classes? Also I feel like if I add an observer to a mesh then the callback function should be aware of the context i.e. the mesh object from which it's called and therefore I shouldn't have to also assign objects to local variables before I can refer to them in the function, but maybe I'm expecting too much. Any pointers on using Observables correctly from within Typescript classes would be most appreciated. @Nockawa @Deltakosh Quote Link to comment Share on other sites More sharing options...
GameMonetize Posted February 21, 2017 Share Posted February 21, 2017 Hello you were pretty close Actually you need to use arrow functions: class MyMesh extends BABYLON.Mesh { private myMeshChild:BABYLON.Mesh; constructor() { // Create child mesh and add some animation etc. this.myMeshChild.onBeforeRenderObservable.add(() => { console.log(this.myMeshChild.rotation); }); } } inteja 1 Quote Link to comment Share on other sites More sharing options...
Nockawa Posted February 21, 2017 Share Posted February 21, 2017 Using the arrow function will guaranty you that you can use "this" inside the function, otherwise "this" is the window object, which is not what you expect/want. inteja 1 Quote Link to comment Share on other sites More sharing options...
inteja Posted February 22, 2017 Author Share Posted February 22, 2017 Ah. Thanks so much! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.