【问题标题】:Backbone.js: How to make the View handle the model's error?Backbone.js:如何让 View 处理模型的错误?
【发布时间】:2012-02-18 05:54:37
【问题描述】:

基本上,我希望我的模型有自己的验证逻辑,同时将错误传递到视图。这是代码和链接: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...

更新:

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

【问题讨论】:

    标签: javascript validation error-handling backbone.js


    【解决方案1】:

    问题出在这里:

    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/

    【讨论】:

    • 我刚才仔细检查时才发现它。感谢您的帮助 :)(当 stackoverflow 允许我时会将您的标记为答案)
    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 2011-12-31
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多