2016-08-12 58 views
0

我有一类设置这样调用方法

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?'); 
    }; 
} 

当数据库发生变化时,控制台写着“哟,东西变了!”如预期。但我的类方法永远不会运行,我不会得到任何错误。如何从pouchdb同步中调用方法?

回答

1

随着这里的回调函数:

on('change', function (change) { 

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

}) 

你所得到的动态this这是从你的类回调分离。

在ES6,现在你只需切换到Arrow功能得到“这个”被词法范围:

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箭头和定时功能的比较。