主干验证功能没有被调用 [英] Backbone validate function not getting called

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

问题描述

我的验证函数没有在下面的代码中被调用:-

My validate function is not getting called in the code below:-

var Vehicle = Backbone.Model.extend({
    color: 'green',
    validate: function (attrs) {
        var validColors = ['white', 'red', 'blue', 'yellow'];
        var colorIsValid = function (attrs) {
            if (!attrs.color) return true;
            return _.contains(validColors, attrs.color);
        }
        if(!colorIsValid(attrs)) {
            return "color must be one of: " +validColors.join(",");
        }
    }
});

var car = new Vehicle();

car.on('error', function (model, error) {
    console.log(error);
});

console.log(car.get('color'));
car.set('color', 'muave');

请看小提琴http://jsfiddle.net/vineet85/Fa8jr/5/

谁能告诉我为什么没有调用验证函数?

Can someone tell me why the validate function is not getting called?

推荐答案

在 Backbone.js 中 validatesave 上自动调用,但在 set.

In Backbone.js validate is called automatically on save but not on set.

如果您希望在设置值时运行验证,则需要使用 validate 选项.例如

If you want validations to run when setting a value you will need to use the validate option. e.g.

car.set('color', 'muave', {validate: true});

http://backbonejs.org/#Model-validate

error 事件在发生错误时触发,通常是在服务器上尝试保存对象时.见 http://backbonejs.org/#Events-catalog

The error event is triggered when an error occurs, typically on the server, when trying to save the object. See http://backbonejs.org/#Events-catalog

如果您想捕获验证失败,请尝试处理 invalid 事件:

If you want to catch validation failures try handling the invalid event:

car.on('invalid', function (model, error) {
    console.log(error);
});

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

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