简体   繁体   English

如果条件为真,则绑定事件,否则立即执行

[英]Bind an event if condition is true or else execute immediately

Is there a known pattern to replace this kind of code : 有没有一种已知的模式可以代替这种代码:

if(condition) {
    $(el).on("event", function() {
        doSomething();
    });
}
else {
   doSomething();
}

Where doSomething is always the same function ? doSomething在哪里总是相同的功能?

Wrap it up? 包起来?

function doBindOrExecute(el, condition, func) {
  if(condition) {
      $(el).on("event", function() {
          func();
      });
  }
  else {
     func();
  }
}

doBindOrExecute(el, true, function() {
  // Do stuff
});

If you're looking for a short convoluted solution you can try something like this. 如果您正在寻找一个简短的复杂解决方案,则可以尝试类似的方法。

$(el).on('event', condition ? doSomething : doSomething() && false);

Using the Ternary Operator , if condition is evaluated as true , it will bind 'event' to the function doSomething . 使用三元运算符 ,如果condition评估为true ,它将把'event'绑定到函数doSomething Otherwise it will invoke doSomething and always use the value false so nothing is actually bound regardless of the return value from doSomething . 否则,它将调用doSomething并始终使用false值,因此无论doSomething的返回值是什么,实际上都没有绑定。

Not the best for readability or maintenance, but you could do: 对于可读性或维护而言,这不是最好的方法,但是您可以

if(condition || doSomething()) {
    $(el).on("event", function() {
        doSomething();
    });
}

as long as doSomething() doesn't return a truthy value. 只要doSomething()不返回真实值。 But wrapping it up is definitely a better way. 但是,将其包装绝对是一个更好的方法。

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

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