在Knockout中,是否可以在观察者的订阅(subscription)接收新值之前获取该可观察对象的当前值?
示例:
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
});
在Knockout中,是否可以在观察者的订阅(subscription)接收新值之前获取该可观察对象的当前值?
示例:
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
});
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) {
});
有一种方法可以像这样订阅先前的值:
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");
this
代表什么? - Thanasis Ioannidis对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;
};
.dispose
只会处理第二个订阅,而不是 'beforeChange'
订阅。 - TRManderson拉取请求 添加这个功能的代码比依赖于使用beforeChange
事件更好。
感谢Michael Best提供了解决方案。
ko.subscribable.fn.subscribeChanged = function (callback) {
var savedValue = this.peek();
return this.subscribe(function (latestValue) {
var oldValue = savedValue;
savedValue = latestValue;
callback(latestValue, oldValue);
});
};
引用 Michael 的话:
我最初建议使用
beforeChange
来解决这个问题,但后来意识到它并不总是可靠的(例如,如果你在 observable 上调用了valueHasMutated()
)。
var enclosedObservable = ko.observable();
this.myObservable = ko.computed({
read: enclosedObservable,
write: function (newValue) {
var oldValue = enclosedObservable.peek();
alert(oldValue);
enclosedObservable(newValue);
}
});
peek()
会给你新的值。 - Michael Tepersubscribe
回调中检索值,这是无法使用peek()完成的。你的例子证明不了什么,反而可能会混淆新手。你基本上是在这里包装一个私有变量,并在设置之前显示其值-因此它当然不会改变。 - Simon_Weaver
dispose()
函数的订阅对象。https://gist.github.com/30ff1f5c1adf215179b0046515f86e45 - Michael