Backbone.js:如何从collection.create获取模型验证错误

时间:2015-04-02 17:55:56

标签: backbone.js

尝试使用collection.create添加模型。我在模型上添加了验证,它的工作原理是当我尝试创建模型时没有任何反应。但是,触发成功或错误回调都没有,页面就在那里。如何获得实际错误? (验证只返回一个像“这是错误的”字符串)

我认为问题在于错误回调仅在服务器返回错误时触发。那你怎么从这里捕获验证错误呢?

self.collection.create({
     //attributes
   }, {
   success: function (model, response) {
       //this doesn't run
   },
   error: function (model, response) {
       //this doesn't run either
   }
});

1 个答案:

答案 0 :(得分:2)

来自文档

  

返回新模型。如果客户端验证失败,则模型将未保存,并带有验证错误

var model = self.collection.create({
     //attributes
   }, {
   success: function (model, response) {
       //this doesn't run
   },
   error: function (model, response) {
       //this doesn't run either
   }
});

现在您可以通过两种方式处理错误:
1)using events

model.on('invalid',function(){
  // error handling here
});


2)using flag

   if(model.validationError){
       // error handling here
        }