Skip to content

Instantly share code, notes, and snippets.

@miguelludert
Created April 18, 2014 17:02
Show Gist options
  • Save miguelludert/11054234 to your computer and use it in GitHub Desktop.
Save miguelludert/11054234 to your computer and use it in GitHub Desktop.
// overrwrite the built in text binding handler to allow for formatting
var origTextHandler = ko.bindingHandlers.text;
var newTextHandler = {
init: origTextHandler.init,
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var bindings = allBindings();
if (bindings.format) {
// if there is a format, do the work to unwrap the value, then process it
var value = ko.unwrap(valueAccessor());
// if there is a format, check to see if it's a function, if so execute it, otherwise pass the value to the formatter
if (_.isFunction(bindings.format)) {
value = bindings.format(value);
} else {
value = newTextHandler.formatter(value, bindings.format);
}
origTextHandler.update(element, function () { return this; }.bind(value), allBindings, viewModel, bindingContext);
} else {
// if there isn't a format, don't mess with perfection, execute the original update
origTextHandler.update(element, valueAccessor, allBindings, viewModel, bindingContext);
}
},
formatter: function (toFormat,format)
{
if (_.isDate(toFormat)) {
// if the value to format is a date, format it with moment
return moment(toFormat).format(format);
} else if (_.isUndefined(toFormat) || _.isNull(toFormat)) {
// if the format is not defined, return nothing
return undefined;
} else {
// if the value to format is defined, but we have no handle for it throw an exception
throw new "Formatting not implemented for type " + typeof (toFormat);
}
}
};
ko.bindingHandlers.text = newTextHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment