Dorian Marchal
Dorian Marchal

Reputation: 635

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 ?

Upvotes: 1

Views: 786

Answers (3)

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

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.

Upvotes: 1

dave
dave

Reputation: 64657

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.

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Wrap it up?

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

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

Upvotes: 1

Related Questions