1

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');
});
Om3ga
  • 30,465
  • 43
  • 141
  • 221

2 Answers2

1

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.

Community
  • 1
  • 1
Pramod
  • 5,150
  • 3
  • 45
  • 46
  • If you evaluate immediately with no parameters you will get an error immediately as attrs is not defined – Tallmaris Oct 21 '12 at 10:34
1

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';
    }
}
Tallmaris
  • 7,605
  • 3
  • 28
  • 58