Reputation: 4863
I have a class setup like this
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?');
};
}
When the database changes, the console reads 'yo, something changed!' as expected. But my class method is never run and I don't get any errors. How do I call a method from inside pouchdb sync?
Upvotes: 0
Views: 219
Reputation: 13495
With a function in the callback here:
on('change', function (change) {
console.log('yo, something changed!');
this.dosomething();
})
You are getting the dynamic this
which is detached from your class in the callback.
In Es6, you can now just switch to an Arrow function to get 'this' to be lexically scoped:
on('change', (change) => {
console.log('yo, something changed!');
this.dosomething();
})
In the past, the usual method was to create a new variable set equal to this
before setting up the callback:
var that = this;
...
on('change', function (change) {
console.log('yo, something changed!');
that.dosomething();
})
A comparison of the arrow and regular function in a JSfiddle here.
Upvotes: 1