繁体   English   中英

Backbone.js:如何使View处理模型的错误?

[英]Backbone.js: How to make the View handle the model's error?

基本上,我希望模型具有自己的验证逻辑,同时将错误传递给View。 这是代码和链接: http : //jsfiddle.net/jancarlo000/aRFGm/3/

结果是“未定义”,而不是“年龄不能为0”

Person = Backbone.Model.extend({
    defaults: {
        'FirstName':'JC'
    },   
    initialize: function(){
        console.log('new person');
    },
    validate: function(attr){
        if (attr.Age == 0){
            return 'age cannot be 0';
        }
    }
});

AppView = Backbone.View.extend({
    initialize: function(){
        this.model.bind('error', function(model, error){ 
                                    alert(model); alert(error); 
                                 }());
    }
});

var j = new Person();
var app = new AppView({model:j});
app.model.set({Age:0}); <=== purposely try to invoke validation error here..

//note: console's target must be result(fiddle.jshell.net) 
//in Chrome for it to work...

更新:

问题是我在函数中添加了不必要的调用运算符()

问题在这里:

AppView = Backbone.View.extend({
  initialize: function(){
    this.model.bind('error', function(model, error){ alert(model); alert(error); }());
  }
});

您不需要立即绑定的绑定函数,请删除括号:

AppView = Backbone.View.extend({
  initialize: function(){
    this.model.bind('error', function(model, error){ alert(model); alert(error); });
  }
});

并运行您的代码: http : //jsfiddle.net/aRFGm/4/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM