Om3ga
Om3ga

Reputation: 32863

backbone validate function does not work

I am using backbone validate function but it gives this error again Uncaught TypeError: Object [object Object] has no method 'apply'. I really have no idea why is it giving me this error.

Here is my code

$(function () {
var Veh = new Backbone.Model.extend({
    validate: function (attrs) {
        var validColors = ['white','red', 'black'];
        var colorIsValid = function (attrs) {
            if(!attrs.color) return true;
            return _(validColors).include(attrs.color);
        }
        if(!colorIsValid(attrs)) {
            return 'wrong color';
        }
    }
});
var car = new Veh();
car.on('error', function (model, error) {
    console.log(error);
});
car.set('foo', 'bar');
});

Upvotes: 1

Views: 884

Answers (2)

Pramod
Pramod

Reputation: 5208

Update: The error is the use of new. Don't do new when using Backbone.extend. This is because you are creating a class and not an object.

$(function () {
var Veh = Backbone.Model.extend({
    validate: function (attrs) {
        var validColors = ['white','red', 'black'];
        var colorIsValid = function (attrs) {
            if(!attrs.color) return true;
            return _(validColors).include(attrs.color);
        }
        if(!colorIsValid(attrs)) {
            return 'wrong color';
        }
    }
});

Notice var Veh = Backbone.Model.extend instead of

var Veh = new Backbone.Model.extend

See this question for the side effects of using new inadvertantly.

Upvotes: 1

Tallmaris
Tallmaris

Reputation: 7590

If you have the unminified version you can step through thte code and see where the error is. What I would do immediately, anyway, is change the param name of the colorIsValid function so it's not the same as the outer function...

validate: function (attrs) {
    var validColors = ['white','red', 'black'];
    var colorIsValid = function (modelAttrs) {
        if(!modelAttrs.color) return true;
        return _(validColors).include(modelAttrs.color);
    }
    if(!colorIsValid(attrs)) {
        return 'wrong color';
    }
}

Upvotes: 1

Related Questions