DEV Community

Dima Kuzmich
Dima Kuzmich

Posted on • Originally published at Medium on

1

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.


Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay