繁体   English   中英

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

[英]Between two event listeners: How do I pass my function without using trigger()?

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

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

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

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

在此处输入图片说明

$("#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();


});

由于两种情况都要求调用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()
});

为什么不只是将函数定义移到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
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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