Reputation: 50742
I am trying to set an object (summary) inside another object's callback method
returnObj.beforeLoadComplete = function (records) {
var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
returnObj.summary = summaryObj;
// some other code which finally returns an object
}
The above code does not work (i.e. summary
is not set on returnObj
)
However if I have the same code outside the callback method, it works as in code snippet below:
var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
returnObj.summary = summaryObj;
returnObj.beforeLoadComplete = function (records) {
// some other code which finally returns an object
}
Not sure why is it so.
Upvotes: 4
Views: 113
Reputation: 22041
You have to access your object with this statement, also i've correct some typo:
var returnObj = {};
returnObj.beforeLoadComplete = function (records) {
var someObj = {
total: {
label: 'Items',
value: '15'
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
// Access object with this
this.summary = someObj;
// some other code which finally returns an object
}
returnObj.beforeLoadComplete('records');
console.log(returnObj.summary);
Update: Added code snippet to verify that returnObj
could be accessed via this in callback handler.
var returnObj = {};
returnObj.beforeLoadComplete = function () {
var someObj = {
total: {
label: "Items",
value: "15"
},
additional: [{
label: 'Item1 Total',
value: '25000'
}]
};
this.summary = someObj;
// some other code which finally returns an object
}
//returnObj.beforeLoadComplete();
function verifyObjectUpdated(){
alert(returnObj.summary);
}
<select onChange="returnObj.beforeLoadComplete()">
<option>Trigger onChange to add summary to your returnObj</option>
<option>Trigger onChange to add summary to your returnObj</option>
</select>
<select onChange="verifyObjectUpdated()">
<option>Trigger onChange to alert summary of returnObj ( do it after adding summary)</option>
<option>Trigger onChange to alert summary of returnObj ( do it after adding summary)</option>
</select>
Upvotes: 5