how to solve 'this' problems with node libraries like async and request how to solve 'this' problems with node libraries like async and request node.js node.js

how to solve 'this' problems with node libraries like async and request


You're doing it exactly right.

The alternative is to keep a reference to the object always in context instead of using bind, but that requires some gymnastics:

Fetcher.prototype.init = function() {    var self = this;    async.parallel([        function(){ return self.getTwitterData() },        function(){ return self.getKloutData() }    ], function() {        console.log('done');    });}Fetcher.prototype.getKloutData = function(callback) {    var self = this;    function saveData() {        // store data        self.blah();    }    request(url, saveData);};

You can also do the binding beforehand:

Fetcher.prototype.bindAll = function(){    this.getKloutData = this.prototype.getKloutData.bind(this);    this.getTwitterData = this.prototype.getTwitterData.bind(this);};Fetcher.prototype.init = function(){    this.bindAll();    async.parallel([ this.getTwitterData, this.getKloutData ], function() {        console.log('done');    });};


You can save this into another variable:

var me = this;

Then me is your this.


Instantiate object with this function:

function newClass(klass) {    var obj = new klass;    $.map(obj, function(value, key) {        if (typeof  value == "function") {            obj[key] = value.bind(obj);        }    });    return obj;}

This will do automatic binding of all function, so you will get object in habitual OOP style,when methods inside objects has context of its object.

So you instantiate you objects not through the:

var obj = new Fetcher();

But:

var obj = newClass(Fetcher);