如何创建在创建时可能无效的主干模型? [英] How do you create a backbone model that might be invalid upon creation?

查看:76
本文介绍了如何创建在创建时可能无效的主干模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法创建主干模型:

I'm trying to create a backbone model using:

var newUser = new App.User({
    name: $('input[name=new_user_name]').val(),
    email: $('input[name=new_user_email]').val()
  });

具有以下验证:

App.User = Backbone.Model.extend({

  validate: function(attrs) {
    errors = [];
    if (_.isEmpty(attrs.name)) {
      errors.push("Name can't be blank");
    }
    if (_.isEmpty(attrs.email)) {
      errors.push("Email can't be blank");
    }

    return _.any(errors) ? errors : null;
  },
...
});

但是,当文本框值为空时,由于验证失败,无法创建模型.

However, when the textbox values are empty, the model can't be created because the validations fail.

是否可以创建模型并运行isValid()以检查值是否正确?还是在创建模型之前还有其他方法可以运行验证?

Is there a way to create a model and run isValid() to check the values are correct? Or is there some other way to run validations before the model is created?

骨干模型创建代码中,它看起来像验证失败时会引发异常Error("Can't create an invalid model"),但是是否可以事先检查验证?

From the backbone model creation code, it appears it throws the exception Error("Can't create an invalid model") upon failing validation, but would it be possible to check validations before hand?

推荐答案

您可以使用silent: true创建无效的模型,但是通过这种方式,集合不会抛出事件'add'.但是您可以将默认选项发送给函数,以在validate()中添加并捕获此选项

You can create unvalid model with silent: true, but in this way collection don`t trow event 'add'. But you can sent default option to function add and catch this option in validate()

collection.add({option:'unvalid_value'}, {validation: false});
Model = Backbone.Model.extend({
  validate: function(attributes, options){
    if (options.validation === false)
      return;
    //Validation code
    //.....       
  }
});

这样,您可以使用无效的哈希创建模型)

This way you can create model with invalid hash)

这篇关于如何创建在创建时可能无效的主干模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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