Knockoutjs Observable Subscription(循环) - 防止用户输入错误的输入

时间:2014-05-25 00:25:05

标签: javascript jquery knockout.js

如果用户输入不符合预期,是否可以“不更改”值?例如,以下代码有效:

function data(sno, exp) {
        var self = this;
        self.sno = ko.observable(sno);
        self.exp = ko.observable(exp);
        self.previousValue = 0;
        self.exp.subscribe(function(param1){
            this.previousValue = param1;
        }, self, "beforeChange");

        self.exp.subscribe(function(param1){
            try {
                this.exp(eval(param1));
            }
            catch(err) {
                this.exp(this.previousValue);
            }
        }, self);
    }

但是,调试这个我意识到当我使用exp更改可观察变量this.exp(this.previousValue);的值时,会再次触发订阅,这会重复几次直到该值与beforeChangechange次活动。有没有办法绕过这种重复?

1 个答案:

答案 0 :(得分:0)

我遵循的方法使用自定义绑定和订阅。此解决方案使用此SO问题/答案的想法:How to define a custom binding who use previous value to determine class in Knockout?

我在这里创建了一个新的小提琴:http://jsfiddle.net/joshnicholson/F4bds/1

以下是小提琴的Javascript摘录。最好访问该链接以查看完整示例:

function subscribeToPreviousValue(observable, fn) {
    observable.subscribe(fn, this, 'beforeChange');
}

function isInvalid(expression) {
    return expression === 'invalid';
}

function data(sno, exp) {
    var self = this;

    self.sno = ko.observable(sno);
    self.exp = ko.observable(exp).extend({throttle: 200});
    self.writeCount = ko.observable(0);
    self.output = ko.observable("");    
    self.log = function(msg) {
        var content = self.output();
        self.output(content + "> " + msg + "<br />");
    };
}

ko.bindingHandlers.bindingWithPrevValue = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var vm = bindingContext.$data,
            observable = valueAccessor(),
            current = observable();

        vm.log('Initial value is ' + current);
        subscribeToPreviousValue(observable, function (previous) {
            var newValue = element.value; 

            if(isInvalid(previous)) return;

            vm.log('');
            vm.log('value changed from ' + previous + ' to ' + newValue);            
            if(isInvalid(newValue)) {
                vm.log(newValue + ' is not valid. reverting...');
                observable(previous);
            }
        });
    }
};

ko.applyBindings(new data("000-11-2222", "testexp"));

在HTML中:

<input type="text" data-bind="value: exp, bindingWithPrevValue: exp" />