Skip to main content

I’m trying to save changes to a model when the user closes the page.  I don’t want to give the user a message, I just want to save the models.  Here is the code that I’m using, but it seems like it’s working only some of the time.  Can someone tell me what I’m doing wrong.  Thanks!

(function(skuid){
var $ = skuid.$;
$(document.body).one(‘pageload’,function(){
         
        $(window).on(‘beforeunload’, function () {
            saveAllModels();
        });
        
});

})(skuid);

    function saveAllModels(){

           var SalesOrderModel = skuid.model.getModel(‘SalesOrder’);
           var savePromise = SalesOrderModel.save();
    }

Timing is always tricky for me. You may want to try a jquery deferred promise, like so:


function saveAllModels(){<br>&nbsp;var dfd = new $.Deferred();<br>// Save all the models on the page (or you can save your single model as you did above)<br>&nbsp;$.when(skuid.model.save(skuid.model.list())).then(function(){<br>&nbsp; dfd.resolve();<br>&nbsp;}<br>&nbsp;return dfd.promise();<br>}

From what I’ve read, this will be quite difficult to accomplish, because model.save() invokes an asynchronous XMLHttpRequest, which is not guaranteed to be initiated or complete before the page is unloaded. See this discussion on navigator.sendBeacon, which describes some hacky potential ways to trick the browser to remaining on the same page long enough for the asynchronous process to complete, none of which are recommended. 

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

Ideally under the hood Skuid’s asynchronous transport methods (save(), load(), etc.) would be able to be configured use sendBeacon instead of normal XMLHttpRequest in the context of unloading the window — but this is not possible right now. 





Reply