Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  156] [ 5]  / answers: 1 / hits: 15463  / 12 Years ago, fri, december 7, 2012, 12:00:00

I have 3 methods



exports.getImageById = function (resultFn, id) {
...
}

exports.getCollectionById = function (resultFn, id) {
}


in the third method I want to call both methods



exports.getCollectionImages = function (resultFn, collectionId) {

var arr = new Array();

this.getCollectionById( // fine, 1st call
function (result) {
var images = result.image;
for (i = 0; i < images.length; i++) {
this.getImageById(function (result1) { // error, 2nd call
arr[i] = result1;
}, images[i]
);

}
}
, collectionId
);

resultFn(arr);
}


I can call first function this.getCollectionById but it fails to call this.getImageById, it says undefined function, whats the reason for that?


More From » node.js

 Answers
33

When you call this.getCollectionById passing it a callback, the callback doesn't have access to the same this



The simplest solution is to save this as a local variable.



exports.getCollectionImages = function (resultFn, collectionId) {    
var arr = new Array();
var me = this; // Save this
this.getCollectionById( // fine, 1st call
function (result) {
var images = result.image;
for (var i = 0; i < images.length; i++) {
// Use me instead of this
me.getImageById(function (result1) { // error, 2nd call
arr[i] = result1;
}, images[i]);
}
}, collectionId);
resultFn(arr);
}

[#81541] Thursday, December 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;