淘汰赛-无法使用订阅更新可观察值(由于扩展程序验证) [英] Knockout - Can't update Observable value using Subscribe (due to extension validation)

查看:65
本文介绍了淘汰赛-无法使用订阅更新可观察值(由于扩展程序验证)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行以下建议,但是每次更新值时,似乎都没有触发所需的反应.这可能是由于我是Knockout的新手而实施的.

I have attempted implementing the suggestions below but neither seemed to trigger the required reaction each time a value was updated. This may due to my implementation as I'm new to Knockout.

我有一个绑定到TextBoxFor的可观察值(金额).

I have an observable (Amount) which is bound to a TextBoxFor.

@Html.TextBoxFor(m => m.Amount, new { type = "number", data_bind = "value: Amount" })

输入值时,需要对其进行验证以确保其不超过999999.此外,如果该值小于50,则需要将其设置为50.每个检查都需要进行一次时间金额"更改.

When a value is entered it needs to be validated to ensure it doesn't exceed 999999. In addition to this, if the value is less than 50 then it needs to be set to 50. These checks needs to be made each time the 'Amount' changes.

var viewModel = {
    Amount: ko.observable().extend({numeric: 0, max: 999999})
};

我已经尝试实现解决方案(在上一篇文章的答案中),但是我无法使它们起作用.

I've tried implementing the solutions (in the answer to my previous post) but I couldn't get these to work.

我想出的最好的办法是创建一个计算如下.这将检查输入值,并在第一次尝试时正确更新.后续的值更改不会触发屏幕上的更改,而是逐步执行代码,似乎确实会更新ViewModel.Amount值.

The best I have come up with is creating a computed as follows. This checks the input value and updates correctly on the first attempt. Subsequent value changes do not trigger a change on the screen but stepping through the code, do seem to update the ViewModel.Amount value.

@Html.TextBoxFor(m => m.Amount, new { type = "number", data_bind = "value: amountMin" })


quoteVehicleViewModel.VehicleMileage = ko.observable(0);


viewModel.amountMin = ko.computed({
    read: function () {
        return viewModel.Amount();  
    },
    write: function (value) {
        if (value < 50) {
            viewModel.Amount(50);
        }
    }
}).extend({ numeric: 0, max: 999999 });

**在控制台中输入的"viewModel.Amount()"将值显示为1000,但屏幕上的值仍将显示为输入的值.

** A "viewModel.Amount()" entered in the Console shows the value as being 1000 but the value on screen still shows as the value entered.

非常感谢收到任何帮助

约翰

推荐答案

据我所知,敲除验证不能直接从规则定义中访问可观察对象.如果可能的话,您可以在自定义验证规则中强制使用该值.

As far as I know knockout validation doesn't provide any ability to access the observable directly from the rule definition. If that were possible you could coerce the value right in a custom validation rule.

我发现最好的替代方法是为您要强制执行的每个规则创建一个自定义扩展器.

The best alternative that I've found is to create a custom extender for each rule you want to coerce.

以下是最小"规则的示例强制扩展器:

Here's an example coercion extender for the "min" rule:

  ko.extenders.coerceMin = function (target, enable) {
      //collect rule values
      var minRule = ko.utils.arrayFirst(target.rules(), function (val) {
          return val.rule === "min"
      });
      if (minRule === null) {
          throw Error("coerceMin extender must be used in conjunction with the 'min' knockout validation rule");
      }
      var minValue = minRule.params;
      //listen for changes and coerce when necessary
      var subscription = null;
      if (enable && !subscription) {
          subscription = target.subscribe(function (newValue) {
              if (!isNaN(newValue)) {
                  var newValueAsNum = parseFloat(+newValue);
                  var valueToWrite = newValueAsNum < minValue ? minValue : newValueAsNum;
                  //only write if it changed
                  if (valueToWrite !== newValue) {
                      target(valueToWrite);
                  }
              }
          });
      } else {
          if (subscription) {
              subscription.dispose();
          }
      }

      //return the original observable
      return target;
  };

您可以像这样在视图模型中应用它:

You can apply it in your view model like so:

var viewModel = {
    Amount: ko.observable()
              .extend({numeric: 0, min: 50, max: 999999})
              .extend({coerceMin: true});
};

这里有个小提琴来演示: http://jsfiddle.net/f2rTR/1/

Here's a fiddle to demonstrate: http://jsfiddle.net/f2rTR/1/

这篇关于淘汰赛-无法使用订阅更新可观察值(由于扩展程序验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆