2016-08-12 49 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箭頭和定時功能的比較。