Skip to content

Instantly share code, notes, and snippets.

@fiveisprime
Last active December 29, 2015 01:39
Show Gist options
  • Save fiveisprime/7595235 to your computer and use it in GitHub Desktop.
Save fiveisprime/7595235 to your computer and use it in GitHub Desktop.
Simplify callbacks using function.bind or var self = lame;
var level = require('level');
//
// Store data from the collector to a leveldb database.
//
var DbController = function(db, collector) {
this.db = level(db);
this.collector = collector;
//
// The data event needs access to the `db` property, but
// rather than storing a reference to `this` (`var _this = this;`),
// the context is bound using function.bind.
//
this.collector.on('data', function(data) {
this.db.put(data.name, data.value, function(err) {
if (err) console.error(err);
});
}.bind(this));
};
//
// Exposes the ability to get data that was persisted from
// the collector.
//
DbController.prototype.get = function(name, fn) {
this.db.get(name, fn);
};
module.exports = function(db, collector) {
return new DbController(db, collector);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment