简体   繁体   中英

Javascript callback function throws error “Callback is not a function” in firefox

function CascadeDropDowns(parentClass, childClass, action, callback) {
  var DropDownId = $(parentClass + " option:selected").val();

  $.ajax({
    url: "/site/" + action,
    data: { DropDownId: DropDownId },
    dataType: "json",
    type: "POST",
    error: function () {
      alert("An error occurred.");
    },
    success: function (data) {
      var items = "";
      $.each(data, function (i, item) {
        items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
      });
      $(childClass).html(items);
      $(childClass)[0].selectedIndex = 0;
      callback();
    }
  });
}

$(document).ready(function () {
  // Populates all child drop downs on load
  var callback = function () {
    CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
  };

  CascadeDropDowns(".DeviceTypeDDL", ".ConfigGroupDDL", "GetGroups", callback);

  // Populates all child drop downs parent change
  $(".DeviceTypeDDL").change(function () {
    var callback = function () {
      CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
    };
    CascadeDropDowns(".DeviceTypeDDL", ".ConfigGroupDDL", "GetGroups", callback);
  });
  $(".ConfigGroupDDL").change(function () {
    CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
  });
});

This runs fine and cascades the dropdowns in the right order, but firefox debugger shows an error and ie throws an alert and asks if Id liek to debug.

Any advice would be great

It is because you are not always passing the callback into that method.

success: function (data) {
  var items = "";
  $.each(data, function (i, item) {
    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
  });
  $(childClass).html(items);
  $(childClass)[0].selectedIndex = 0;
  if(callback) callback();  //check before calling it. 
}

It's because you are not always providing a callback to the CascadeDropDowns function.

Eg

CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");

You should modify your function to treat the callback argument as an optionnal argument:

if (callback) {
    callback();
}

A common shorthand for that is:

callback && callback();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM