簡體   English   中英

使用淘汰賽和打字稿。 如何更改可觀察對象的訂閱值?

[英]Using Knockout & Typescript. How can I change the value of an Observable from its subscription?

使用淘汰賽和打字稿。 如何更改可觀察對象的訂閱值?

我正在使用Typescript重構KO舊代碼,並且發現這段代碼是可觀察的,並使用“ this”更新它,而TypeScript無法實現。

let utils = new Utils();

utils.subscribeFilterAlphanumeric = function(val){
    var newVal = utils.filterAlphanumeric(val);
    this(newVal); 
    // "this" in regular JS is the observable
    // "this" in Typescript is the Class "Utils"
};

myObservable = ko.observable();
myObservable.subscribe(utils.subscribeFilterAlphanumeric , myObservable);

有什么建議如何使它在Typescript中起作用嗎?

謝謝 !

在TypeScript中,可以通過使用=>來控制什么是“ this”。

class x {
    public myObservable: KnockoutObservable<any>;

    constructor(){
        this.myObservable = ko.observable<any>();
        this.myObservable.subscribe(function(val){
            // Not using => this remains myObservable
            var newVal = utils.filterAlphanumeric(val);
            this(newVal); 
        })
    }
}

應該可以

Ko.Extensders這是一個很好的解決方案

http://knockoutjs.com/documentation/extenders.html

我建立:

ko.extenders.filter = function (target, filterType) {
    if (filterType == "number") { 
        wUtils.observableSubscribeFilterNumber(target);
    }
    return target;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM