DEV Community

Dima Kuzmich
Dima Kuzmich

Posted on • Originally published at Medium on

KnockoutJS simple truncate text binding handler

Hello everyone,

On my current project I needed to truncate text in some titles. Since we’re using KnockoutJS, I decided to write custom binding handler. And so I did.

Custom binding handlers are great solution, that provides you with ability to control how your observables interact with DOM elements. In addition you encapsulate your custom behaviors, thus they became reusable. It’s very useful when you use third party widgets that need to be updated all the time when observable values are updated.

So here is an example of my truncate binding handler:

ko.bindingHandlers.truncatedText = {
 update: function (element, valueAccessor, allBindingsAccessor) {
 var originalText = ko.utils.unwrapObservable(valueAccessor()),
 // 10 is a default maximum length
 length = ko.utils.unwrapObservable(allBindingsAccessor().maxTextLength) || 20,
 truncatedText = originalText.length > length ? originalText.substring(0, length) + “…” : originalText;
 // updating text binding handler to show truncatedText
 ko.bindingHandlers.text.update(element, function () {
 return truncatedText; 
 });
 }
};

You can try it here

Use this binding handler and use binding handlers in general.

Enjoy.


Top comments (0)