Jump to content

Questions about using Observables in typescript


inteja
 Share

Recommended Posts

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

Link to comment
Share on other sites

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);
    });
  }
}

 

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...