Knockout JS Update Color

落花浮王杯 提交于 2019-12-22 13:49:31

问题


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/



来源:https://stackoverflow.com/questions/10589681/knockout-js-update-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!