0

I created a simple example of my problem

The function count should count the numbers of items that I receive back from a query. However the way I am currently implementing it I lose reference to my function when I call from the route. In this case the function doWork is from another node module that I cannot modify.

Is there anyway to get around this

function Counter(){
    this.array = createArray();
};


Counter.prototype.count = function (q){

query(q, function(data){
    if(data ===  "tabe")
    {
            this.array[0].total++;
    }
    else
    if(data === "chair")
    {
            this.array[1].total++;
    }
    else
    if(data === "lamp")
    {
            this.array[2].total++;

    }
    });
};

createArray = function (){

    var array = [];     

    array.push({item : "table",
                        total: 0});
    array.push({item : "chair",
                        total: 0});
    array.push({item : "lamp",
                        total: 0});    
    return array;

};

//The query function is actually in another node module that I cannot edit
query = function( data, callback){
    callback(data);
}    

module.exports = Counter;

index.js file

 /* Process query */    
router.get('/submit', function(req, res, next) {

    var counter = new Counter();

    counter.count("table");
    counter.count("table");
    counter.count("lamp");    


    for(var i = 0; i  < counter.array.length; i++){
        console.log(counter.array[i]);
    }

    res.end();
});
dfann
  • 95
  • 1
  • 1
  • 7

1 Answers1

1

It is because the execution context of the callback method is not referring to the Counter instance, you can use the Function.bind() to pass a custom context to the callback method.

Counter.prototype.count = function (q) {
    query(q, function (data) {
        if (data === "tabe") {
            this.array[0].total++;
        } else if (data === "chair") {
            this.array[1].total++;
        } else if (data === "lamp") {
            this.array[2].total++;

        }
    }.bind(this));
};

Another option is to use a closure variable

Counter.prototype.count = function (q) {
    var self = this;
    query(q, function (data) {
        if (data === "tabe") {
            self.array[0].total++;
        } else if (data === "chair") {
            self.array[1].total++;
        } else if (data === "lamp") {
            self.array[2].total++;

        }
    });
};
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531