Skip to content

Commit

Permalink
update messageTemplate binding to allow singluar/plural forms
Browse files Browse the repository at this point in the history
  • Loading branch information
gschueler committed Apr 21, 2016
1 parent b8da6e0 commit 3d8090f
Showing 1 changed file with 13 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
* Placeholders are in the form '{0}','{1}', etc. The "messageTemplate" binding value can be a single value, which
* will be used for {0}, or it can be an object with a 'value' property, possibly observable, containing an array
* for the replacement values.
* If a binding "messageTemplatePluralize: true" is set, then the template text is treated as a singular and a plural
* version of the same text, separated by "|" character. If the first bound data value is "1", then singular form
* is used, otherwise the plural form is used.
*
*/
ko.bindingHandlers.messageTemplate = {
Expand All @@ -14,8 +17,15 @@ ko.bindingHandlers.messageTemplate = {
return { 'controlsDescendantBindings': true };
},
update:function(element, valueAccessor, allBindings, viewModel, bindingContext){
var pluralize=allBindings.get('messageTemplatePluralize');
var data=ko.utils.unwrapObservable(valueAccessor());
var template=jQuery(element).data('ko-message-template');
var pluralTemplate=null;
if(pluralize){
var arr = template.split('|');
template = arr[0];
pluralTemplate = arr[1];
}
var values=[];
if(typeof(data)!='object'){
values=[data];
Expand All @@ -30,6 +40,9 @@ ko.bindingHandlers.messageTemplate = {
for(var i=0;i<values.length;i++){
values[i] = ko.utils.unwrapObservable(values[i]);
}
if(pluralize && values[0]!=1){
template=pluralTemplate;
}
var text = template.replace(/\{(\d+)\}/g,function(match, g1, offset, string){
var val= parseInt(g1);
if(val>=0 && val<values.length){
Expand Down

0 comments on commit 3d8090f

Please sign in to comment.