简体   繁体   中英

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 ?

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 . Otherwise it will invoke doSomething and always use the value false so nothing is actually bound regardless of the return value from 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. But wrapping it up is definitely a better way.

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