简体   繁体   中英

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/

In this context this is the window object and not 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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