ASync Save Support

by tomprogramming

HTML

<button id="ajax-button">Add an Ajax Request</button>
<button id="non-ajax-button">Add a non-ajax request</button>
<button id="save">Save</button>

JavaScript

var Application = {};
Application.Editor = {};

///flag to determine if the actual save continues
var continueWithSave = true;
///API to allow any plugin to stop the save
Application.Editor.StopSave = function(){
  continueWithSave = false;
}

///mock method to just serve up an ajax request
///this would be any plugin's specific code to do what it needs to do
var ajaxNum = 0;
var getAjax = function(){
  var myAjaxNum = ajaxNum;
  console.log('ajax request ' + myAjaxNum + ' started');
  ajaxNum++;
  return  $.ajax({
            url: '/echo/html/',
            success: function(data) {
                console.log('ajax request complete ' + myAjaxNum);
              //if you need to stop save from actually happening
              //just call
              //Application.Editor.StopSave();
            }
        });
};

///mock method to serve up something that is not an ajax request
///this would be any plugin's specific code to do what it needs to do 
var nonAjaxNum = 0;
var getNonAjax = function(){
  console.log('non-ajax request ' + nonAjaxNum + ' started');
  
  var now = new Date();
  now.setSeconds(now.getSeconds() + 5);
  while((new Date()).value !== now.value){
      var x = 1;
  }
  console.log("non-ajax done " + nonAjaxNum);
  nonAjaxNum++;
  return { not : "an ajax request" };
};


///the actual "SAVE" code would go in here
///to be executed after all requests have finished
 var globalCallback = function(){
    if (continueWithSave){
      console.log("all requests done");
    }else{
      console.log("save was stopped by a request");
    }
   
  }
  
  
 ///internal array to keep track of functions that have been pushed on the "before you save" stack
  var saveStack = [];

///API to push a function onto the save stack
Application.Editor.BeforeSave = function(fn){
  saveStack.push(fn);
}
  
/// The function to kick off the before save requests and the final callback
Application.Editor.doSave = function(){
  var requests = [];
    //reset our mutex lock
  ...