Jez
Jez

Reputation: 30071

How do change binding handler based on a condition?

I want to use a different binding handler for a table column based on a condition, for example:

<tbody data-bind="foreach: plansList">
    <tr>
        <td data-bind="numVotes > 0 ? (html: voteOptionLinked) : (text: voteOption)"></td>

In one case, there is a link that I want to bind using the html handler but in the other case I just want to display it using the text handler. The above doesn't work because the handler: has to come at the beginning of the data-bind attribute, but is there a way I can do this in Knockout?

Upvotes: 0

Views: 61

Answers (2)

Ray
Ray

Reputation: 3959

You could use a custom binding:

ko.bindingHandlers.customBinder = {
    init: function(element, valueAccessor, allBindings) {
        
    },
    update: function(element, valueAccessor, allBindings, viewModel) {
        var numVotes = valueAccessor();
        if (numVotes() > 0){
          var html = viewModel.voteOptionLinked;
          element.innerHTML = html;
        }
        else {
          var text = viewModel.voteOption;
          element.textContent = text;
        }
    } 
};

// ----------------------------------------------------------------------------
// Page viewmodel



function SurveyViewModel() {
    this.numVotes = ko.observable(4);
    this.voteOptionLinked = '<span>ab</span><span>dfsdf</span>';
    this.voteOption = 'zzzzzz';
}

ko.applyBindings(new SurveyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="customBinder:numVotes">

</div>

Upvotes: 0

Ray
Ray

Reputation: 3959

A workaround, but it achieves what you want:

<tr>
    <!-- ko if: numVotes() > 0 -->
        <td data-bind="html: voteOptionLinked"></td>
    <!-- /ko -->
    <!-- ko ifnot: numVotes() > 0 -->
        <td data-bind="text: voteOption"></td>
    <!-- /ko -->
</tr>

Upvotes: 1

Related Questions