首页 文章

Knockoutjs只验证chind类

提问于
浏览
0

我使用Knockoutjs 3.0.0和Knockoutjs-Validate,大部分时间它们都能很好地工作 . 现在,当我尝试验证部分View模型时,我遇到了问题 . 像这样:

function DataViewModel() {
      var self = this;

      self.username = ko.observable("").extend({ required: {message:"User name is required!" }});
      self.password = ko.observable().extend({ required: {message:"Password is required!" }});

      self.login = function () {

          if (self.isValid()) {
              self.errors.showAllMessages();
              return false;
          }
           $("#loginform").submit();
      };
  }

我还有控制页面属性的Page Viewmodel .

function PageViewModel(){
    var self=this;
    self.contentheader=ko.observable("Login");
    self.usernamelabel = ko.observable("User Name");
    self.passwordlabel = ko.observable("Password");
  }

我像这样创建ViewModel:

function ViewModel()
  {
    var self=this;
    self.data= ko.validatedObservable(new DataViewModel());
    self.page= new PageViewModel();
  }

最后我绑定到KO var vm = new ViewModel(); ko.applyBindings(VM);

为什么我这样做的程序是:在DataViewModel中,我存储将从服务器传递或加载的数据,我控制此页面的页面视图模型行为,我应该在用户向服务器提交数据时验证DataViewModel . 但它不起作用,我看到KO模型像这样引发错误

TypeError: obsv is undefined

有人可以帮忙吗?

1 回答

  • 1

    在您的情况下,您可以在该模型中处理 DataViewModel 的验证 . 在模型中添加一个observable来跟踪验证,就像这样

    self.errors = ko.validation.group(self);

    并将主视图模型中的 DataViewModel 实例更改为普通 ko.observable 而不是经过验证的observable . 我made a fiddle with the complete code .

相关问题