Answer the question
In order to leave comments, you need to log in
Why is the scope variable lost during the callback?
There is an html page parser that puts data into the DB, with a callback (below). On one page there are several options that must be entered in the table separately. I iterate over them with
$(...).each, then check if the key product_id-option_id exists in the table, updating or writing the new data.
...
"callback":function(error,result,$) {
if (error) {
logger.error(error);
return;
}
logger.info('(%d/%d) Url %s %d', this.idx, this.total, this.uri, result.statusCode);
if (result.statusCode!=200) {
return;
}
// $ is a jQuery instance scoped to the server-side DOM of the page
var product_new = {
product_id: this.product_id
};
// options
$("#pr .option").each(function(index,a)
product_new.option_id = $(a).data('opt')||0;
logger.debug('>> pid=%d, opt=%d',product_new.product_id, product_new.option_id);
Product.find({product_id: product_new.product_id, option_id: product_new.option_id||0}).success(function(product_old){
logger.debug(index);
logger.debug('<< pid=%d, opt=%d',product_new.product_id, product_new.option_id);
});
});
}
[Friday, January 31, 2014 11:52:59,379] DEBUG >> pid=76, opt=13
[Friday, January 31, 2014 11:52:59,379] DEBUG >> pid=76, opt=308
[Friday, January 31, 2014 11:52:59,380] DEBUG >> pid=76, opt=310
[Friday, January 31, 2014 11:52:59,380] DEBUG >> pid=76, opt=311
[Friday, January 31, 2014 11 :52:59,502] DEBUG 0
[Friday, January 31, 2014 11:52:59,503] DEBUG << pid=76, opt=311
[Friday, January 31, 2014 11:52:59,789] DEBUG 2
[Friday, January 31 , 2014 11:52:59,789] DEBUG << pid=76, opt=311
[Friday, January 31, 2014 11:52:59,793] DEBUG 3
[Friday, January 31, 2014 11:52:59,793] DEBUG << pid =76, opt=311
[Friday, January 31, 2014 11:52:59,802] DEBUG 1
[Friday, January 31, 2014 11:52:59,802] DEBUG << pid=76, opt=311
Answer the question
In order to leave comments, you need to log in
For example, just do at the beginning of each()
var product_id = product_new.product_id,
option_id = product_new.option_id;
callback is called once -> there is only one context -> product_new is defined in it -> shared by all nested functions
anonymous from each() is called for each element -> every time its own context in which index is defined -> anonymous from success() has access to that index, which is defined in the same context as it
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question