Formatters that only run when the triggering value changes

Today, we have these great formatters to display values/string in a different way. However, these formatters seems to constantly (re)run even if the base value/string has not changed.

For example, if you create a custom formatter that simply console logs and returns you can see if just keeps running.

dmx.Formatter('string', 'tester', function (str) {
    console.log('formatter run');
    return str;

Screen Shot 2021-09-13 at 11.36.17 AM

No big deal until there are dozens/hundreds of more complicated formatters running on a page.

Is it possible for the formatter to only run once when it is initialized and not run again until the dynamic data using the formatter changes, or is updated?

Where do you want to use it for? The formatters are just for formatting data, they are not actions that are triggered. If you want to trigger a function on a value change then place a hidden input on the page and bind the action to the updated event, that will only trigger when the value was changed.

I suppose it is a request to enhance performance really. I shy away from using the formatters simply because when used with large datasets, it slows everything down. The page is so busy constantly formatting the exact same thing, that it loses its snappy feel when the user takes action.

But in this case, it really must be done client side. I am displaying up to a few dozen ingredients. Each ingredient has a quantity and unit of measure (gram, oz, tsp, etc). The user can dynamically change the number of servings so each of the ingredients needs to be recalculated on each serving change.

The calculation however is not just simple math. It also determines the best unit of measure (eg. switch from tablespoons to cups as it gets larger ) and then converts to an appropriate fraction rather than decimal (display 1/2 instead of.5)

It is working and is not the worst page I’ve had in terms of performance. It just got me thinking…why constantly perform this formatting when the results can never change?

I think the only place where you could gain performance are the array/collection formatters. With formatters you normally can assume that when the input parameters are the same then the output is also the same, so you could cache this output and reuse it the next time the formatter is called with exactly the same parameters.

1 Like

Here a version of your tester formatter that only logs when value was changed.

dmx.Formatter('string', 'tester', (function() {
  var lastValue = null;
  return function(str) {
    if (str !== lastValue) {
      lastValue = str;
    return str;

Thanks Patrick, much appreciated.