model.data disappears

  • 1
  • Question
  • Updated 2 years ago
  • Answered
I've created a javascript snippet where I collect selected Opportunities and populate a new model using those Opportunity Id's as a condition. 

var childModel = skuid.$M('childModel');
var childModelCondition = childModel.getConditionByName('Opportunity__c', false);
childModel .setCondition(childModelCondition, oppIds, false);
childModel .updateData();

This works fine. I then take that new model and pass it into a method on a static resource. I have three console.logs in the code immediately, and over the course of those three lines of javascript I lose my data...

inside the method:
console.log(childModel); //this shows a data attribute with several rows.
console.log('childModel data');
console.log(childModel.data); //this returns an empty array.
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb

Posted 2 years ago

  • 1
Photo of Ben Hubbard

Ben Hubbard, Employee

  • 12,470 Points 10k badge 2x thumb
This is an unfortunate result of how console.log works in Chrome or other browsers. If you console.log an object like "childModel", chrome will just log a reference to that object, not the actual state of that object at the time you logged it. So for your first console log, it's just showing the later state of your childModel. However, when you log childModel.data, it's showing the actual state of that property at the time of your logging.

The real problem is that childModel.updateData() is an asynchronous function. It does not complete before subsequent lines of code are called.

If you call your method from inside the callback or the then() method of the updateData call, you should be fine...

// Promise Method
childModel.updateData().then(function(){
    console.log(childModel.data);
});
or

// Callback Method
childModel.updateData(function(){
    console.log(childModel.data);
});
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb
lol thank you. I was just about to post that I found the issue and used a .then to make it work :)