Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a custom binding who use previous value to determine class in Knockout?

I need to bind a table with knockout, and I would like the table cell to get a different css class if the new value is higher or lower of the previous.

I have in mind different possibilities, such as storing the previous value in the bindingContext and have a function which returns the right class, but is it possible to add a custom binding handler which receives the previous value and the new value?

like image 215
Edmondo1984 Avatar asked Feb 18 '23 10:02

Edmondo1984


2 Answers

Although Jeff's and Sławomir's answers would work, I found an alternative that doesn't need any change to the view model nor relies on altering the DOM element object.

function subscribeToPreviousValue(observable, fn) {
  observable.subscribe(fn, this, 'beforeChange');
}

ko.bindingHandlers['bindingWithPrevValue'] = {
  init: function (element, valueAccessor) {
    var observable = valueAccessor();
    var current = observable();

    console.log('initial value is', current);

    subscribeToPreviousValue(observable, function (previous) {
      console.log('value changed from', previous, 'to', current);
    });
  }
};

Naturally, that will only work if the bound property is an observable.

like image 192
jpbochi Avatar answered May 01 '23 16:05

jpbochi


I looked into knockout source and I suppose that you can't access previous value inside update method of bindingHandler but you can store it inside element

ko.bindingHandlers['bindingWithPrevValue'] = {
    update: function (element, valueAccessor) {
        var prevValue = $(element).data('prevValue');
        var currentValue = valueAccessor();
        $(element).data('prevValue', currentValue());

        // compare prevValue with currentValue and do what you want
    }
};
like image 20
Sławomir Rosiek Avatar answered May 01 '23 14:05

Sławomir Rosiek