在两个事件侦听器之间:如何在不使用trigger()的情况下传递函数?

时间:2018-10-04 16:19:56

标签: javascript jquery bootstrap-modal

请查看我的图表以及下面的伪代码。我试图弄清楚如何在两个事件侦听器之间传递函数。

基本上,如果“可用性”小于0,或者当用户在引导对话框中单击“确认”时,我想执行一些代码。如果“可用性”大于0,则将显示特殊的引导对话框。

我试图避免两次编写相同的代码。我还试图避免使用触发器$("#btnConfirm").trigger("click", fn1); ---我的假设是,有一种更性感的方式,例如回调或类似的东西……

所以......如何将要执行的代码放入另一个“按钮单击”事件侦听器中,或者如何将“ btnConfirm”返回到调用对话框的事件侦听器中? / p>

enter image description here

$("#Select").on("change", function(e) {

  fn1 = function() {
    //stuff I want to do
  };

  //a check that must be passed
  currAvail = $("#Availability").val();

  if (currAvail > 0) {
    //show a message, "Are you sure you want to make the thing?"
    //if YES, execute fn1()
    //fn1() needs to be available to btnConfirm click listener
    // use trigger("click", fn1) ????



  } else {

    //execute the code
    fn1();

  };

});

$("#btnConfirm").on("click", function(e, param1) {

  //Ok, well, they said YES...
  //so I need to execute fn1();


});

2 个答案:

答案 0 :(得分:2)

由于在两种情况下都要求调用fn1(),因此您可以将逻辑分离为方法,并在需要时调用

function fn1() {
  //code to execute on no goes here
}
$("#Select").on("change", function(e) {
  let currAvail = $("#Availability").val();
  if (currAvail > 0) {
    //show modal window
  } else {
    //execute the code
    fn1();
  };
});
$("#btnConfirm").on("click", function(e, param1) {
  fn1()
});

答案 1 :(得分:1)

为什么不将函数定义移至change回调之外?

$("#Select").on("change", function(e) {
  //a check that must be passed
  currAvail = $("#Availability").val();

  if (currAvail > 0) {
    //show a message, "Are you sure you want to make the thing?"
    //if YES, execute fn1()
    //fn1() needs to be available to btnConfirm click listener
    // use trigger("click", fn1) ????

  } else {
    //execute the code
    fn1();
  };
});

$("#btnConfirm").on("click", function(e, param1) {
  //Ok, well, they said YES...
  //so I need to execute fn1();
});

// Function move to here.
function fn1() {
  //stuff I want to do
};