0

I think I'm either misunderstanding or missing something when it comes to Javascript callbacks.

$(document).ready(function () {
   reload_Editables(loadTab());
}
function reload_Editables(callback) {
   var xeditables = ["Description", "Type", "GTIN"];
   $.each(xeditables, function (i, val) {
      $("#" + val).editable({
        inputclass: "form-control",
        success: function (response, newValue) {
            itemPageModel.set(val, newValue);
        }
     });
   });
   debugger;
   callback();
}
function loadTab() {
   if ($('#Type').text().toUpperCase() == 'TEST') {
       $('#test-tab').show();
   }
}

What I expected to have happen is loadTab to be passed into reload_Editables and only executed on callback. Instead loadTab is completing first (before even the first line of reload_Editables) and callback is undefined. What am I doing wrong?

Natalka
  • 258
  • 1
  • 14
  • 1
    `reload_Editables(loadTab());` -> `reload_Editables(loadTab);` See also: [addEventListener calls the function without me even asking it to](https://stackoverflow.com/q/16310423) – VLAZ Dec 08 '20 at 14:02
  • 1
    To clarify, putting `()` on a function executes it, there and then. If your wanting to pass a function to execute later, pass without the `()`. – Keith Dec 08 '20 at 14:03
  • In addition, if you need to pass parameters, you can also type `reload_Editables(function(){ loadTab(...params); });` – kosmos Dec 08 '20 at 14:07

1 Answers1

1

You're passing the result of calling your callback rather than a reference to the callback itself

This:

$(document).ready(function () {
   reload_Editables(loadTab());
}

should be

$(document).ready(function () {
   reload_Editables(loadTab);
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193