简体   繁体   English

取消订阅 observable 的函数方法

[英]function method to unsubscribe from observable

Cannot read property 'unsubscribe' of undefined无法读取未定义的属性“取消订阅”

function record(){
    this.event
}
record.prototype = {
    start: function (){
        keyUp = Rx.Observable.fromEvent(document, "keyup");
        this.event = keyUp.subscribe((key) => {console.log(key)});
    },
    stop: function (){
        this.event.unsubscribe();
    }
}

rec = new record();
rec.start();
setTimeout(rec.stop, 2000);

https://jsfiddle.net/yn70k2g9/ https://jsfiddle.net/yn70k2g9/

In this context this is the window object and not record .在这种情况下this是 window 对象而不是record

function record(){
    event;
}
record.prototype = {
    start: function (){
        keyUp = Rx.Observable.fromEvent(document, "keyup");
        record.event = keyUp.subscribe((key) => {console.log(key)});
    },
    stop: function (){
        record.event.unsubscribe();
    }
}

rec = new record();
rec.start();
setTimeout(rec.stop, 2000);

https://jsfiddle.net/yn70k2g9/5/ https://jsfiddle.net/yn70k2g9/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM