4

好像在 rxjs 4.x 中,Rx.Observable.fromCallback 接受 scope 作为第二个参数,但是在 5.0 中,这个方法改为 Rx.Observable.bindCallback 并且不接受 scope 参数。如何在 bindCallback 中添加范围参数。例如在 ES6 中。

class Test {
  constructor(input) {
    this.input = input;
  }

  callback(cb) {
    return cb(this.input);
  }

  rx() {
    // this works on rx 4.x
    // var observable = Rx.Observable.fromCallback(this.callback, this)();

    // this doesn't work, because this.callback function doesn't use original this, so cannot get this.input
    var observable = Rx.Observable.bindCallback(this.callback)();

    // Work around: Rx.Observable.bindCallback(this.callback)();
    // var me = this;
    // var observable = Rx.Observable.bindCallback((cb) => {me.callback(cb);})();

    observable.subscribe(
      input => console.log('get data => ' + input),
      err => console.log('get error =>' + err),
      () => console.log('complete')
    );
   }
  }

  new Test(100).rx();
4

2 回答 2

4

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindCallback有一个示例,它显示了如何执行此操作。

在对象方法上使用 bindCallback

const boundMethod = Rx.Observable.bindCallback(someObject.methodWithCallback); boundMethod.call(someObject) // make sure methodWithCallback has access to someObject .subscribe(subscriber);

您可以在不声明变量的情况下立即调用它,也可以像这样传递参数:

Rx.Observable.bindCallback(someObject.callback).call(someObject,<args>)

所以绑定到this你可以简单地调用

Rx.Observable.bindCallback(this.callback).call(this,<args>)
于 2017-04-15T22:33:19.333 回答
1

当我将它添加到构造函数时,它对我有用

  constructor(input) {
    this.input = input;
    this.callback = this.callback.bind(this)
  }
于 2016-03-28T08:49:07.870 回答