主干验证不起作用 [英] Backbone Validate does not work

查看:25
本文介绍了主干验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Backbone 的 validate 函数来保证 Manage 属性大于 18.这是我的代码:

I am using Backbone's validate function to guarantee Man to have an age property more than 18. Here is my code:

var Man = Backbone.Model.extend({
    initialize : function(){
        this.on("error",function(model,error){
            alert(error);
        });
    },
    validate : function(attrs,options){
        if (attrs.age < 18){
            return 'below 18';
        } 
    }
})

var man = new Man({name : 'qian', age : 12});

但从结果来看,validate 似乎不起作用.

But looking at the result it seems that validate doesn't work.

推荐答案

在 Backbone.js(0.9.10 之前的版本)中,validate 之前被调用>saveset 之前一样.

In Backbone.js (prior to version 0.9.10), validate is called before save as well as before set.

当您设置 invalid 值时,您将收到 alert 错误.

You will get an alert error when you set invalid value.

示例 - age 值低于 18 :

Example - age value is below 18 :

var man = new Man ({name : 'qian', age : 12});
man.set({ age: 12 }); // that will trigger alert

编辑

对于 Backbone.js 版本 0.9.10+ 报告了一个问题:验证失败不触发错误回调.问题解释说

For Backbone.js version 0.9.10+ there is an issue reported: Failed validation does not trigger error callback. Issue explanation says that

invalid 事件代替 error

因此将您的代码更改为:

So changing your code to:

var Man = Backbone.Model.extend({
    initialize : function(){
        this.on("invalid",function(model,error){
            alert(error);
        });
    },
    ...

并且将 validate 选项设置为 true 的变量设置将触发 alert.

And setting variable with validate option set to true will trigger an alert.

man.set({age: 12}, {validate : true});

这篇关于主干验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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