admin管理员组

文章数量:1320612

In Knockout is there a clean way to display a boolean property from my view model to show 'Yes' or 'No' instead of True / False. Sometimes the property is undefined so this should also show No.

Currently using :

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

Must be a better way.

In Knockout is there a clean way to display a boolean property from my view model to show 'Yes' or 'No' instead of True / False. Sometimes the property is undefined so this should also show No.

Currently using :

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

Must be a better way.

Share Improve this question edited May 29, 2015 at 7:36 José Ricardo Pla 1,04310 silver badges16 bronze badges asked May 29, 2015 at 6:49 Alan AlcockAlan Alcock 7872 gold badges11 silver badges27 bronze badges 2
  • if(!bool || typeof bool == undefined) bool='No'; else bool='Yes'; ? Don't see why you would replace fully functional boolean values though. – JazzCat Commented May 29, 2015 at 6:53
  • Apologies @JazzCat. Hope my edit makes clarifies my question. You can see what I am trying to achieve from the markup. – Alan Alcock Commented May 29, 2015 at 7:05
Add a ment  | 

2 Answers 2

Reset to default 8

You could use this custom bindingHandler,

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 so,

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

Thanks

if you define isAvailable as observable you can easily achieve it by:

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: don't forget to use () when dealing with observable value

本文标签: javascriptYes or No instead of True or False in KnockoutStack Overflow