0

In my jQuery script I need for comboboxes :

  1. On focus event, run code in order to get all values before the user changes the value inside this <select>.
  2. On change event, run code depending a json object built during focus event

script

var previousDataObject = [];

$('body').on('focus', "select.my-combobox", function () {
     comboboxChangeInit(); // it fills previousDataObject up;  
}).on( "change", "select.my-combobox", function(){ 
     //here code using previousDataObject 
});

The basic jQuery behaviour will run focus and change on user actions.

In my case, I need to wait comboboxChangeInit() fills previousDataObject up completly to run the code on change event.

How can I create a kind of listener to do this ?

J.BizMai
  • 2,621
  • 3
  • 25
  • 49
  • Have `comboChangeInit()` return a promise. Store that promise in a variable outside of the handler. And the in the change event handler, attach a `then()` to that promise. – Taplar Jul 17 '19 at 21:45
  • I´m trying to understand what you´re saying. Can you give me a generic piece of code to be clearer for me ? – J.BizMai Jul 17 '19 at 21:48

2 Answers2

0

You can try using trigger instead, so

$('body').on('focus', "select.my-combobox", function () {
     comboboxChangeInit(); // it fills previousDataObject up;
     $(this).trigger('change')
}).on( "change", "select.my-combobox", function(){ 
     //here code using previousDataObject 
});

trigger will fire the event passed as argument, please check the jQuery Docs

Juorder Gonzalez
  • 1,642
  • 1
  • 8
  • 10
  • I tried your example. With your code, the trigger run "change" event even if the user has just opened the combobox but did not select another value yet. If I display a spinner inside "Change" event, the spinner appears after "focus" without the user changed the value. – J.BizMai Jul 18 '19 at 13:36
0

I found a solution based on deferred object thanks this question.

jQuery

var previousDataObject = [];

var previousDataDeferred;

$('body').on('focus', "select.my-combobox", function () {
     comboboxChangeInit(); // it fills previousDataObject up.  
}).on( "change", "select.my-combobox", function(){ 
   var myObject = $(this); 
   $.when( previousDataDeferred ).done(function(){ 
         //Display spinner for example
         //here code using myObject and previousDataObject.
         //Remove spinner and reset previousDataObject  
   });
});

function comboboxChangeInit(){
   previousDataDeferred = $.Deferred();
   //Code to fill previousDataObject up.
   previousDataDeferred.resolve();
});
J.BizMai
  • 2,621
  • 3
  • 25
  • 49