Save model javascript callback function

  • 2
  • Question
  • Updated 2 years ago
  • Answered
I have a table on my page, with a rowaction to show a popup. There are a series of action steps before the popup: Show message, Activate and set a condition, Create a new row, Query model, Run a snippet, Show popup.

The javascript snippet conditionally creates a new row in another model and then saves the row. That row is critical to subsequent activity in the popup dialogue. This is what the javascript looks like (without the conditional coding):
var myModel = skuid.model.getModel('MyModel');
myModel.createRow();
myModel.save();
My understanding is that the save() runs asynchronously, that is, the snippet will complete even if the save is delayed. Potentially, the popup could open and user activity take place without the new row in MyModel. Would a callback function prevent that?

What I have in mind is this change to the save statement:
myModel.save( { callback: function(result) { saveIsDone(result) }} );
function saveIsDone(result) {}
Will a null/empty function such as saveIsDone() be sufficient to force the snippet to wait for the save to complete? Or, do a series of action steps actually continue anyway, so that the popup is already being displayed while the snippet runs?

(And is there any way to test the scenario, that is, to force a delay in saving the myModel row?)


Photo of Mike Dwyer

Mike Dwyer

  • 3,390 Points 3k badge 2x thumb

Posted 2 years ago

  • 2
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Mike,

jQuery deferred promise is your friend, here.

do something like this in your snippet:

var myModel = skuid.model.getModel('MyModel'),
    $ = skuid.$,
     dfd = new $.Deferred(); myModel.createRow(); $.when(myModel.save()) .done(function(){ dfd.resolve(); }) .fail(function(){ dfd.reject(); console.log('save failed'); }); return dfd.promise();
Photo of Mike Dwyer

Mike Dwyer

  • 3,390 Points 3k badge 2x thumb
Excellent! Thanks, Matt. I had looked at JQuery deferred promise but wasn't sure how to use it. This will be very helpful.

Can I assume that the code shown will not complete until the new row is safely in the database?

And, in the Action Framework, will a Run A Snippet action need to complete before the next action in a sequence is performed?
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
right. nothing inside the .done() or .fail() functions will run until the action inside the $.when() completes.

and the action sequence will not continue until the promise is returned.
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb