在订阅相同的观察值时获取先前的可观察值
在获得新价值之前,是否有可能在淘汰赛中获得可观察项目内的可观察项目的现值?
例:
this.myObservable = ko.observable(); this.myObservable.subscribe(function(newValue){ //I'd like to get the previous value of 'myObservable' here before it's set to newValue });
有一种方法可以像这样对之前的值进行订阅:
this.myObservable = ko.observable(); this.myObservable.subscribe(function(previousValue){ //I'd like to get the previous value of 'myObservable' here before it's set to newValue }, this, "beforeChange");
ko.subscribable.fn.subscribeChanged = function (callback) { var oldValue; this.subscribe(function (_oldValue) { oldValue = _oldValue; }, this, 'beforeChange'); this.subscribe(function (newValue) { callback(newValue, oldValue); }); };
使用上面这样的:
MyViewModel.MyObservableProperty.subscribeChanged(function (newValue, oldValue) { });
对Beagle90的答案几乎没有改变。 总是返回订阅本身以便能够访问dispose()。
ko.subscribable.fn.subscribeChanged = function (callback) { var oldValue; this.subscribe(function (_oldValue) { oldValue = _oldValue; }, this, 'beforeChange'); var subscription = this.subscribe(function (newValue) { callback(newValue, oldValue); }); // always return subscription return subscription; };
添加此function的拉取请求具有一些不同的代码,比依靠使用beforeChange
事件更好。
迈克尔·贝斯特解决scheme的所有功劳
ko.subscribable.fn.subscribeChanged = function (callback) { var savedValue = this.peek(); return this.subscribe(function (latestValue) { var oldValue = savedValue; savedValue = latestValue; callback(latestValue, oldValue); }); };
引用Michael的话:
我最初build议使用
beforeChange
来解决这个问题,但后来才意识到它并不总是可靠的(例如,如果你在observable上调用valueHasMutated()
)。
我发现我可以从一个可写的计算观察值调用peek()来获得之前的值。
像这样的东西(见http://jsfiddle.net/4MUWp ):
var enclosedObservable = ko.observable(); this.myObservable = ko.computed({ read: enclosedObservable, write: function (newValue) { var oldValue = enclosedObservable.peek(); alert(oldValue); enclosedObservable(newValue); } });