Selection box model with typescript and knockout

2019-09-16 05:28发布

问题:

I am new to typescript and will like to convert the following Knockout+js to knockout+typescript. The Knockout+js is working, however I am still failing to make it work with typescript....

View:

<select data-bind="options: choices, value: selectedChoice"></select>

Model:

var MyModel = {
    choices: ["Blue", "White", "Black", "Yellow"],
    selectedChoice: ko.observable("Yellow") 
};

MyModel.selectedChoice.subscribe(function(newValue) {
   alert("the new value is " + newValue); 
});


ko.applyBindings(MyModel);

Typescript:

import BaseVM = require("./BaseVM");

class MyModel extends BaseVM {
  choices = ko.observableArray(["one", "two", "three"]);

  //Here selectedChoice subscribe in typescript...

}

export = MyModel;

回答1:

In typescript from within the class you'll need to put your subscription code inside of a constructor function. Then you can use "this" to access the property you want to subscribe to.

class MyModel extends BaseVM {
    choices = ko.observableArray(["one", "two", "three"]);
    selectedChoice = ko.observable("Yellow");

    constructor() {
        this.selectedChoice.subscribe(function (newValue) {
            alert("the new value is " + newValue);
        });
    }
}