拒绝可观察到的价值变化

Ale*_*lex 6 knockout.js

有没有办法拒绝/取消修改可观察价值?像这样:

observable.subscribe (function (newvalue) {
   if ( newvalue < 0 ) {

        // cancel changing
   }
   else{ 
        // proceed with change
   }

}, this)
Run Code Online (Sandbox Code Playgroud)

And*_*oth 8

编辑:

我发现了其他东西:可写的计算可观察量.

这是一个例子:

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
    });
}
Run Code Online (Sandbox Code Playgroud)

那么你绑定到计算字段.

/编辑

我会选择自定义绑定.

以下是自定义绑定的教程:http://learn.knockoutjs.com/#/? tutorial = custombindings

或者这里是文档:http: //knockoutjs.com/documentation/custom-bindings.html