javascript $.each loop not executing

  • 1
  • Question
  • Updated 2 years ago
  • Answered
I'm attempting to loop through the rows in a model I have in javascript. Here is the code I'm running:

var params = arguments[0], $ = skuid.$;
console.log('Oh Yeah!!!');
var modelStuff = skuid.model.getModel('modelName');
console.log(modelStuff);
$.each(modelStuff.data,function(i,row) {
    console.log('Oh No!!!');
});
console.log(modelStuff);

Both of my console.log(modelStuff) calls before and after the loop show that the model has two rows with data, but I never get 'Oh No!!!'

This is basically copy pasta straight from an example found in another question here. How can I show data (2 rows to be exact) in both of my console.logs but not ever execute the loop on modelStuff.data....
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb
  • frustrated

Posted 2 years ago

  • 1
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb
Also, if I run modelStuff.getRows() it returns an empty array....
Photo of Ben Hubbard

Ben Hubbard, Employee

  • 12,490 Points 10k badge 2x thumb
Hi Jerry,

It looks like the weird logging behavior that you're seeing is because of how your browser's console works. In reality, at the time your code runs, the model has no rows. When you log a reference to the model, Chrome's console is actually showing you the state of the model at a later time.

How is that snippet being invoked? Is it part of a row action?
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb
Thanks Ben, and yes. The snippet I'm running gets called when things are added to that model. I've actually gotten past this and was just about to update this question.

I solved my problem by wrapping the whole thing in one of these guys:

$.when(modelStuff.updateData()).then(function(){
       things and stuff;
});

Not sure how to mark a question solved though...
(Edited)
Photo of Ben Hubbard

Ben Hubbard, Employee

  • 12,490 Points 10k badge 2x thumb
Glad you figured it out. Actually, you don't actually need to use $.when() in this case. Since updateData() returns a promise, you should be able to just use the code below...

modelStuff.updateData().then(function(){
   //things and stuff;
});
Photo of Jerry

Jerry

  • 1,150 Points 1k badge 2x thumb
Cool, I'll give that a try.