Yes or No instead of True or False in knockout

Knockout has a clean way of displaying a boolean property from my viewmodel to show Yes or No instead of True / False. Sometimes the property is undefined, so this should show No.

Currently used:

<td data-bind="text: isAvailable ? 'Yes' : 'No'"></td>

      

There must be a better way.

+3


source to share


2 answers


You can use this custom bindHandler,

ko.bindingHandlers.YesNo = {
    update: function (element, valueAccessor) {
        // defaults to false
        var val = ko.utils.unwrapObservable(valueAccessor()) || false; 

        if (val)
            $(element).text("Yes");
        else
            $(element).text("No");
    }
}

      

Use it like this,



<td data-bind="YesNo: isAvailable"></td>

      

thank

+5


source


if you define isAvailable

as observable, you can achieve this easily:

JSFIDDLE

ViewModel

var viewModel = function()
{
   var self = this;

   self.isAvailable = ko.observable(false);
};

      



View

<td data-bind="text: $root.isAvailable() ? 'Yes' : 'No'"></td>

      

p / s: remember to use ()

when working with observable

+1


source







All Articles