2012-10-21 111 views
1

我正在使用骨干验证功能,但它又给出了这个错误Uncaught TypeError: Object [object Object] has no method 'apply'。我真的不知道为什么它给了我这个错误。骨干验证功能不起作用

这里是我的代码

$(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'); 
}); 

回答

1

更新:该错误是使用新的。在使用Backbone.extend时不要做新的事情。这是因为你正在创建一个类而不是一个对象。

$(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'; 
     } 
    } 
}); 

通知 var Veh = Backbone.Model.extend而不是

var Veh = new Backbone.Model.extend 

this问题,使用新的无意中的副作用。

+0

如果你不带参数立即评估你会立即得到一个错误的ATTRS没有定义 – Tallmaris

+0

@Tallmaris对不起我的错误。我已经更新了答案。 – Pramod

1

如果您有未经验证的版本,则可以逐步验证代码并查看错误的位置。我会马上去做,反正就是改变colorIsValid功能的帕拉姆名称,以便它不一样外功能...

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