【问题标题】:Using Knockout & Typescript. How can I change the value of an Observable from its subscription?使用淘汰赛和打字稿。如何从订阅中更改 Observable 的值?
【发布时间】:2016-04-19 00:56:39
【问题描述】:

使用淘汰赛和打字稿。如何从订阅中更改 Observable 的值?

我正在使用 Typescript 重构一个 KO 旧代码,我发现这段代码订阅了一个 observable 并正在使用 TypeScript 无法实现的“this”对其进行更新。

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 中进行这项工作有任何建议吗?

谢谢!

【问题讨论】:

    标签: javascript knockout.js typescript observable subscribe


    【解决方案1】:

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

    应该可以正常工作

    【讨论】:

    • 在这种情况下是的,但我不知道为什么,但是如果你在一个函数中,Typescript 对“this”的处理方式与箭头函数不同。
    • 查看 TypeScript 编译器生成的带有和不带有 => 符号的回调的 .js 代码非常有启发性。如果您使用 =>,则会在回调代码中生成并替换一个“_this”成员。我认为如果您看那里,您会看到针对您特定情况的解决方案。
    【解决方案2】:

    Ko.Extenders 这是一个很好的解决方案

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

    我创造了:

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

    【讨论】:

      猜你喜欢
      • 2018-06-05
      • 1970-01-01
      • 2012-09-20
      • 2013-04-14
      • 2019-03-28
      • 2012-10-09
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多