0
<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.

Drew H
  • 4,699
  • 9
  • 57
  • 90

1 Answers1

3

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.

Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212
  • Thanks for the help, but even though it has application logic there is view logic involved, being that I don't want the name to show up as a link if they can't do anything anyway. I guess I could just disable it. – Drew H Nov 30 '12 at 17:36
  • Yes exactly. Would just disabling it be the best bet? – Drew H Nov 30 '12 at 18:56
  • Ok, I've updated the answer so that a plain text span is shown if isOwner = false. – Judah Gabriel Himango Nov 30 '12 at 19:52