Skip to content

Instantly share code, notes, and snippets.

@adamrecsko
Created March 27, 2014 11:45
Show Gist options
  • Save adamrecsko/9805741 to your computer and use it in GitHub Desktop.
Save adamrecsko/9805741 to your computer and use it in GitHub Desktop.
Knockout binding for cut text to the required length. It is a require js module. If it less then specified length then cut it and concatenate the trailing to the end of string.
define(['knockout'],function(ko){
ko.bindingHandlers.cuttext = {
update: function (element, valueAccessor,allBindingsAccessor) {
var length = allBindingsAccessor().length || 4294967295; //SAFE MAX_INT
var trailing = allBindingsAccessor().trailing || "";
var value = ko.utils.unwrapObservable(valueAccessor());
if (length<value.length){
value = value.substr(0,length)+trailing;
}
$(element).text(value);
}
};
};
/*
Examples:
with trailing:
<div data-bind="cuttext:yobservable , length: 300, trailing:'...'"></div>
without trailing:
<div data-bind="cuttext:yobservable , length: 300"></div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment