copenndthagen
copenndthagen

Reputation: 50742

Javascript setting object property inside object callback

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

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

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

soyuka
soyuka

Reputation: 9105

Just use this inside your object:

var res = {
  foo: 'bar',
  setSmth: function(data) {
    this.summary = data
  }
}

res.setSmth({bar: 'foo'})

console.log(res.summary)

See jsfiddle

Upvotes: 1

Related Questions