Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call an object instance method using typescript and knockout

I'm trying to do something simple using Typescript and knockout, but can't get it to work. As my codebase of typescipt grows, it seems my viewmodels are growing and need te be nicely modeled in main classes and sub classes. Typescript is perfect for it! In combination with knockout I ran into an annoying problem/bug/situation .... Any help appreciated!!! Here's some typescript code:

class subClassA {
  counter  =0;
  incCounter(){
    this.counter++;
    console.log("counter incs: "+this.counter);
  }
}

class MainViewModel {
  a = new subClassA();


  constructor(){
    this.a.incCounter(); // this works...
  }
  incCounterIndirect(){
    this.a.incCounter(); // this works....
  }
}
ko.applyBindings(new MainViewModel() );

HTML:

<a data-bind="click: $root.incCounterIndirect ">Indirect does work</a>
<a data-bind="click: $root.a.incCounter ">Direct does NOT work</a>

Obviously I need the 'direct' route to work, ie .. calling methods on subClasses directly from the data-bind. Otherwise I need to make proxy members on the mainviewmodel for each subclass/member ...

Which binding prefix or whatever other trick could do the job of calling the member of object A from the click handler.

Any help appreciated, Paul

like image 650
Paul0515 Avatar asked Nov 30 '25 09:11

Paul0515


1 Answers

Use instance members with the fat arrow (introduced in TS 0.9.x) to overcome this scoping issues with prototype members :

class subClassA {
  counter=0;
  incCounter= ()=>{  // Notice difference
    this.counter++;
    console.log("counter incs: "+this.counter);
  }
}

class MainViewModel {
  a = new subClassA();


  constructor(){
    this.a.incCounter(); 
  }
  incCounterIndirect= ()=>{    // Notice difference
    this.a.incCounter(); 
  }
}
ko.applyBindings(new MainViewModel() );
like image 97
basarat Avatar answered Dec 02 '25 23:12

basarat