Text data-bind expressions can have only a single property. How would I pluralize some text depending on the count of another property?
Use -ies or -s (depending on the second-to-last letter) if the word ends in a y, use -es if the word ends in a ‑s, -ss, -sh, -ch, -x, or -z, use a lookup table if the world is an irregular plural, and use -s otherwise.
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding. For more complex bindings, it helps to better understand the behavior and syntax of Knockout's binding system.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
There are several ways to do this. I demonstrated 2 ways in the fiddles shown here: http://jsfiddle.net/njj2P/2/
The first option I showed is to use a ko.computed to determine if the name should be returned in singular or plural form, based on an evaluation.
this.formattedName = ko.computed(function() {
return this.qty() > 1 ? this.name() + "s" : this.name();
}, this);
The second option shows how to do this without a computed property, and instead by using a conditional binding.
<span data-bind="if:qty()>1">s</span>
You can create a reusable custom binding like the following.
ko.bindingHandlers.pluralize = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
function count(data) {
var value = ko.utils.unwrapObservable(data);
if (typeof value === "object" && value.length > 0) {
return value.length;
} else if (typeof value === "number") {
return value;
}
}
var settings = valueAccessor();
var text = count(settings.data) === 1 ? settings.singular : settings.plural;
$(element).text(ko.utils.unwrapObservable(text));
}
};
You would use it like this.
<span data-bind="pluralize: { data:items, singular:'entry', plural:'entries' }"></span>
data
option can point to any array or number.singular
option represents the text you want to display if data
evaluates to 1plural
option represents the text that will be displayed otherwise.See it in action here. http://fiddle.jshell.net/jessegavin/wamfw/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With