4

I have something like this: $('#select1').on('change', function() {}) and it works fine. However, I need to run another function after the function has completed.

I thought about taking the function contents, and putting it in a named function, then taking the second function and doing the same, and placing them in the anonymous function:

$('#select1').on('change', function() {
    function1 ();
    function2 ();
});

However, I was hoping there was another way. The above seems inconsistent with jQuery.

nobrandheroes
  • 748
  • 1
  • 10
  • 17
  • More information would probably be helpful here. If `function1` is a state change and `function2` updates the presentation, you might look at using publish/subscribe or the observer pattern. – aebabis Mar 27 '15 at 20:02

3 Answers3

1

Though you could nest functions with callbacks, generally the best practice in jQuery is to use jQuery.Deferred.

var function1 = function() {

    var deferred = $.Deferred();

    //Do your thing. When finished, call deferred.resolve()

    return deferred;
}

var function2 = function() {

   //Function 2 code
}

$('#select1').on('change', function() {

    function1().then(function2);
});
gregnr
  • 1,222
  • 8
  • 11
0

why dont you try jquery change function insted javascript bind

$( "#select1" ).change(function() {

function1(); function2()

});

frontich
  • 11
  • 6
0

Try this:

$('#select1').on('change', function() {
    function1(someVariable, function() {
      function2(someOtherVariable);
    });
});


function function1(param, callback) {
  //...do stuff
  callback();
} 

Here is where I found that: Call a function after previous function is complete

Community
  • 1
  • 1