来自 pouchdb sync 的调用方法

Call method from pouchdb sync

我有这样的class设置

class FinanceDB {

  constructor() {
    this.PouchDB = require('pouchdb');
    this.db = new this.PouchDB('fin'); //8080
    this.remoteDB = new this.PouchDB('http://localhost:5984/rfin');

    this.db.sync(this.remoteDB, {
      live: true,
      retry: true
    }).on('change', function (change) {

      console.log('yo, something changed!');
      this.dosomething();

    }).on('error', function (err) {
      console.log("error", err);
      // yo, we got an error! (maybe the user went offline?)
    })
  };

  dosomething() {
    console.log('what now?');
  };
}

当数据库更改时,控制台按预期读取 'yo, something changed!'。但是我的 class 方法永远不会 运行 并且我没有收到任何错误。如何从 pouchdb sync 内部调用方法?

这里回调函数:

on('change', function (change) {

  console.log('yo, something changed!');
  this.dosomething();

})

您正在获取与回调中的 class 分离的动态 this

在 Es6 中,您现在只需切换到箭头函数即可使 'this' 具有词法作用域:

on('change', (change) => {

  console.log('yo, something changed!');
  this.dosomething();

})

过去,通常的方法是在设置回调之前创建一个等于this的新变量集:

var that = this;
...
on('change', function (change) {

  console.log('yo, something changed!');
  that.dosomething();

})

JSfiddle here.

中箭头函数与正则函数的比较