有沒有辦法拒絕/取消對observable值的修改? 像這樣:拒絕可觀察值變化
observable.subscribe (function (newvalue) {
if (newvalue < 0) {
// cancel changing
}
else{
// proceed with change
}
}, this)
有沒有辦法拒絕/取消對observable值的修改? 像這樣:拒絕可觀察值變化
observable.subscribe (function (newvalue) {
if (newvalue < 0) {
// cancel changing
}
else{
// proceed with change
}
}, this)
編輯:
我發現別的東西:可寫的計算觀測。
下面是一個例子:
function AppViewModel() {
this.field = ko.observable("initValue");
this.computedField = ko.computed({
read: function() {
return this.field();
},
write: function (value) {
if(value > 0) {
this.field(value);
}
},
owner: this
});
}
,那麼你綁定到計算字段。
/編輯
我會去用自定義綁定。
下面是自定義綁定的教程: http://learn.knockoutjs.com/#/?tutorial=custombindings
或這裏的文檔: http://knockoutjs.com/documentation/custom-bindings.html
爲了拒絕寫值我用下面的:
我伸出淘汰賽與此代碼:
ko.conditionedObservable = function (initialValue, condition) {
var obi = ko.observable(initialValue);
var computer = ko.computed({
read: function() { return obi(); },
write: function (newValue) {
//unwrap value - just to be sure
var v = ko.unwrap(newValue);
//check condition
if (condition(v)) {
//set it to the observable
obi(v);
}
else {
//reset the value
computer.notifySubscribers();
}
}
});
return computer;
};
使用它的對象是這樣的:
field = ko.conditionedObservable<number>(null, (v) => parseInt(v) > 0);