遇到对象方法未按预期运行的问题。当我运行时ndData.recipe()
,它会按预期更新ndData.recipeData
对象,向以前的值添加新值。
但是当我调用ndData.update()
,然后ndData.recipe()
再次运行时,不是将新值添加到旧值中,而是将旧值替换为新值。
我认为我的错误可能与变量范围不当有关,但我不确定。
var ndData = {
initData: null,
newData: null,
recipeData: null,
ingredients : 0,
load : function(NDB_No){
var options = [];
$.getJSON(('scripts/jsonencode.php?q=' + NDB_No), function(data) {
$.each(data.measurements, function(key, val) {
options.push('<option id="wgt' + val.Seq + '" value="' + val.Gm_Wgt + '">'+ val.Amount + ' ' + val.Msre_Desc + '</option>');
options.join('');
$('#servSelect').html(options);
});
ndData.initData = data;
ndData.newData = data;
ndData.recipeData = data;
ndData.print(ndData.initData, '#ndDataTbl');
});
},
print : function(pdata, div){
var items=[];
var options=[];
var wtRatio = 1;
$.each(pdata.properties, function(key, val) {
if ($.isNumeric(val)){
val = Math.round((val * wtRatio)*10)/10;
}
items.push('<tr>');
items.push('<td id="">'+ key +" : " + val + '</td>');
items.push('</tr>');
});
$(div).html((items.join('')));
},
//Seems that when this update() function is called, ndData.recipeData is set to ndData.newData
update : function(){
var GmWt = ($('#servSelect').val())*($('#servQty').val());
var wtRatio = GmWt/ndData.initData.properties.GmWt_1;
$.each(ndData.newData.properties, function(key, val) {
if ($.isNumeric(val)){
parseFloat(val);
parseFloat(wtRatio);
val = Math.round((val * wtRatio)*10)/10;
}
ndData.newData.properties[key] = val;
});
console.log('update val: ' + ndData.newData.properties.Refuse_Pct);
ndData.print(ndData.newData, '#ndDataTbl');
},
recipe : function(){
if (ndData.ingredients > 0){
console.log("inregedients > 0");
$.each(ndData.newData.properties, function(key, val){
if($.isNumeric(val)){
val = parseFloat(val);
ndData.recipeData.properties[key] = parseFloat(ndData.recipeData.properties[key]);
ndData.recipeData.properties[key] += val;
console.log('val: ' + ndData.recipeData.properties[key]); // after ndData.update() is called,
// this is logging the value of ndData.newData.properties[key]
}
});
}else{
console.log("inregedients == 0");
ndData.recipeData = ndData.newData;
}
// after calling ndData.update(), this is printing properties of ndData.newData,
// when I expect properties of ndData.recipeData
ndData.print(ndData.recipeData, '#recipeDataTbl');
ndData.ingredients++ ;
}
};