Knockout-2.2.0, subscribe get value before change AND new value

后端 未结 3 1522
我在风中等你
我在风中等你 2021-02-12 16:59

jsfiddle link: http://jsfiddle.net/T8ee7/

When I call Knockout\'s subscribe method is there a way I can get both the previous and new value? Right now, I can only call g

3条回答
  •  我在风中等你
    2021-02-12 17:18

    I prefer using an observable extender.

    http://jsfiddle.net/neonms92/xybGG/

    Extender:

    ko.extenders.withPrevious = function (target) {
        // Define new properties for previous value and whether it's changed
        target.previous = ko.observable();
        target.changed = ko.computed(function () { return target() !== target.previous(); });
    
        // Subscribe to observable to update previous, before change.
        target.subscribe(function (v) {
            target.previous(v);
        }, null, 'beforeChange');
    
        // Return modified observable
        return target;
    }
    

    Example Usage:

    // Define observable using 'withPrevious' extension
    self.hours = ko.observable().extend({ withPrevious: 1 });
    
    // Subscribe to observable like normal
    self.hours.subscribe(function () {
        if (!self.hours.changed()) return; // Cancel if value hasn't changed
        print('Hours changed from ' + self.hours.previous() + ' to ' + self.hours());
    });
    

提交回复
热议问题