Knockout JS Update Color

2019-05-21 06:58发布

问题:

I'm using Knockout observables to update span values located within table cells. I need to change the background color of the table cell when the new value is different from the old value. It seems when i subscribe to the observable i do not have access to the old value during an update. Is there a way to get the old value? I was planning to update the table cell background using the css binding with a state observable.

<td data-bind="css: { tempIncreased: tempState() > 0 }">
    <span data-bind="text: temp"></span>
</td>

In the View Model:

   this.temp.subscribe(function (newValue) {
        var old = this.temp();
        if (newValue > old) {
            this.tempState = 1;
        }
        else {
            this.tempState = 0;
        }
    }, this);

回答1:

Knockout 2.0 added the ability to subscribe on a topic to observables. The "beforeChange" topic will provide you with the previous value.

With this you can extend observables to add a subscription that provides both the old and new values to the callback.

It could look like:

ko.observable.fn.beforeAndAfterSubscribe = function(callback, target) {
    var _oldValue;
    this.subscribe(function(oldValue) {
        _oldValue = oldValue;
    }, null, 'beforeChange');

    this.subscribe(function(newValue) {
        callback.call(target, _oldValue, newValue);
    });
};

You could add this function to ko.subscribable.fn rather than ko.observable.fn to be able to do this for both computed and normal observables.

You would use this like:

this.temp.beforeAndAfterSubscribe(function (oldValue, newValue) {
    if (newValue > oldValue) {
        this.tempState = 1;
    }
    else {
        this.tempState = 0;
    }
}, this);

Here is a sample: http://jsfiddle.net/rniemeyer/QDbUk/



标签: knockout.js