如何在TypeScript中订阅更改Knockout Observable?

时间:2015-03-17 02:47:37

标签: knockout.js typescript observable

如何在TypeScript中订阅更改Knockout Observable?

Data :Knockoutobservable<string> = ko.Observable<string>();

我需要类似的东西:

Data.subscribe(function(e){})??

2 个答案:

答案 0 :(得分:4)

类型脚本是编写JavaScript的方法。淘汰没有任何区别。

因此,您可以按照以下方式编写订阅(与javascript相同)

Data.subscribe(function(newValue) {
    alert(newValue);
});

答案 1 :(得分:1)

这个打字稿......

class Car {
    data:KnockoutObservable<string>;

    constructor(data: string) {
        this.data = ko.observable(data);
        this.data.subscribe((newData) => {
            alert("My data changed to: " + newData);
        });
    }
}

将编译为以下JavaScript ...

var Car = (function () {
    function Car(data) {
        this.data = ko.observable(data);
        this.data.subscribe(function (newData) {
            alert("My data changed to: " + newData);
        });
    }
    return Car;
})();