简体   繁体   English

如何在Backbone.js中设置单个属性集(验证)

[英]How can I do a single attribute set in Backbone.js (validation)

Yesterday, after researching quite a bit I found that if I want to not set individual attributes on my backbone model (and have validation) then I need to send {silent: true} . 昨天,经过相当多的研究,我发现如果我不想在我的骨干模型上设置个别属性(并进行验证),那么我需要发送{silent: true} That being said we also found out that in the next release of backbone.js silent: true will actually still run validate. 话虽如此,我们还发现在backbone.js的下一个版本中, silent: true实际上仍会运行validate。

The problem with this is that validate blocks set from actually setting the attributes. 这个问题是验证块设置实际设置属性。 So if we don't have silent:true then there is no point of having a set method that accepts single attributes. 因此,如果我们没有沉默:true那么就没有必要设置一个接受单个属性的set方法。 To work around this our validate method looks something like this: 要解决此问题,我们的验证方法如下所示:

validate : function(attrs) {
    var errors = {};
    if (typeof attrs.first_name !== 'undefined' && !attrs.first_name) {
        errors.first_name = "First name can't be empty";
    }
    ...
    if (!_.isEmpty(errors)) {
        return errors;
    }
}

This causes save to not work. 这导致保存不起作用。 So then we decided to write something like this: 那么我们决定写这样的东西:

if (_.isEmpty(attrs)) {
    attrs = this.attributes;
}

The problem with that is if you have attributes sent in on save then you need to merge them in, which I guess is ok, but this is all a decent amount of work to get some simple validation to work/or not run. 问题是如果你在保存时发送了属性,那么你需要将它们合并进去,我想这是可以的,但这是一个相当大的工作量,可以让一些简单的验证工作/不运行。 Furthermore unless I override _validate I need to do it on every model. 除非我覆盖_validate,否则我需要在每个模型上执行此操作。

Is there a better way to do this? 有一个更好的方法吗?

Backbone by default extends the old attributes with the old ones here: https://github.com/documentcloud/backbone/blob/master/backbone.js#L574 Backbone默认使用旧的属性扩展旧属性: https//github.com/documentcloud/backbone/blob/master/backbone.js#L574

As so, only new attributes could break the validation method. 因此,只有新属性才能破坏验证方法。

Here, I think your problem is that you tie too much of your validation to the presence of all attributes, while you're not setting them all at the same time. 在这里,我认为您的问题是,您将过多的验证与所有属性的存在联系在一起,而您并未将它们全部设置在同一时间。 As so, you should make sure the other attributes are allowed to be set as undefined . 因此,您应确保允许将其他属性设置为undefined

example: 例:

// Check if name is set, ignore otherwise
if( attr.name && attr.name !== "Santa" ) { return "Can't be Santa"; }

Another solution is to give every attribute a valid default value. 另一种解决方案是为每个属性提供有效的默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM