Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

backbone.js - Backbone validate function not getting called

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');

Please see fiddle http://jsfiddle.net/vineet85/Fa8jr/5/

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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});

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

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...