Drew H
Drew H

Reputation: 4739

Conditionally bind a function in Knockoutjs

<div data-bind="foreach: passengers">                       
<a href="#" data-bind='style: { color: isOwner  ? "orange" : "darkgreen" }, 
text: person_username, click: function() { $root.removePassenger($data, $parent); } '>


Say I have a template like this. The click function should only be bound if isOwner is true. Is there a simple/easy way to do this? I'm guessing I could break out the full jquery templating and get something done, but I'd like to know a more elegant solution.

Thanks.

Upvotes: 0

Views: 3181

Answers (1)

Judah Gabriel Himango
Judah Gabriel Himango

Reputation: 60001

What you're asking for -- handle a click event only when some property is set -- is application logic. Application logic does not belong in the view. It belongs in the view model.

Sure, you could do something like:

click: function() { if ($data.isOwner) $root.removePassenger($data, $parent); }

But, again, that's putting logic in your view, which is frowned upon from a separation-of-concerns and debugging point of view, and it uglifies your HTML.

I'd suggest doing it like this:

<div data-bind="foreach: passengers">                       
   <a href="#" data-bind='style: { color: isOwner  ? "orange" : "darkgreen" }, 
      text: person_username, click: function() { $root.removePassengerIfApplicable($data, $parent);"</a>
</div>

And your JavaScript:

function removePassengerIfApplicable(passenger, parent) {
    if (passenger.isOwner) {
        removePassenger(passenger, parent);
    }
}

UPDATE

It wasn't clear from your post that you didn't want to show a link if isOwner = false. Here's some updated code for you:

<div data-bind="foreach: passengers">  
   <div data-bind="if: isOwner">                     
      <a href="#" style="color: orange" 
      text: person_username, click: function() { $root.removePassenger($data, $parent); }"</a>
   </div>
   <div data-bind="if !isOwner()">
      <span style="color: darkgreen" data-bind="text: person_username"></span>
   </div>
</div>

The above code shows a link if isOwner, and a plain text span if not.

Upvotes: 3

Related Questions