Last active
December 29, 2015 01:39
-
-
Save fiveisprime/7595235 to your computer and use it in GitHub Desktop.
Simplify callbacks using function.bind or var self = lame;
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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