【发布时间】:2014-06-11 10:29:36
【问题描述】:
我正在对我的用户名和密码进行简单的验证。我的模型在这里:
define(["backbone"], function(Backbone){
var LoginModel = Backbone.Model.extend({
url:'/home',
defaults:{
userName:'',
password:''
},
initialize:function(){
this.bind("change", this.attributesChanged);
},
validate:function(attrs){
var errors = [];
if(attrs.userName < 5){
errors.push({"name": 'userName', "message": 'Please fill email field.'});
}
if(!attrs.password){
errors.push({"name": 'password', "message": 'Please fill feedback field.'});
}
return errors.length > 0 ? errors : false;
},
attributesChanged : function(){
var valid = false;
if (this.get('userName') && this.get('password')) {
valid = true;
this.trigger("validated", valid);
}
else {
this.trigger('invalid', valid); //triggers the invalid works fine.
}
}
});
return LoginModel;
});
但在视图中,我仍然得到那个触发器,但我无法让视图的元素突出显示输入:
这是我的看法:
define([
'jQuery','underscore',
'backbone','marionette',
'text!./templates/loginView.html'],
function($,_,Backbone,Marionette,template){
"use strict";
var LoginView = Backbone.Marionette.ItemView.extend({
className:'col-xs-12 col-md-4 col-md-offset-4',
template:_.template(template),
events:{
"submit form" : "loginSubmit"
},
initialize:function(params){
this.model.view = this;
this.model.bind("validated", this.validated);
this.model.bind("invalid", this.showErrors);
},
loginSubmit:function(e){
e.preventDefault();
var form = e.target,
data = Backbone.Syphon.serialize(form);
var that = this;
var options = {
success: function (model,response) {
if(response){
console.log('success', response)
} else {
console.log('failed')
}
},
error: function(model, options){
console.log("error", xhr.responseText);
}
};
this.model.save(data, options);
// this.model.on('invalid', function(model, error) { console.log(model,'\n', error); })
},
validated:function(value){
console.log(value);
},
showErrors:function(model, error){
var form = this.$el.find('form'); // i am not able to get form element here... what is the issue?
_.each(error, function(value, key){
var input = form.find('input[name='+value.name+']').addClass('error');
input.after('<span class="errorMsg">'+value.message+'</span>');
});
},
hideErrors:function(msg){
console.log('login success!');
},
onShow:function(){
$('input:text').first().select();
}
});
return LoginView;
}
);
我对这部分感到困惑,任何帮助我理解:
1) 如何区分是'validate'方法还是'server'的错误
2) 如何正确处理这两者?
3)什么是正确的方法,我在这里发布了什么?
我在这方面不是很有经验,有没有专家可以帮助我继续我的应用程序开发?
不要让我看一些书,我遇到了请帮助我从我的代码中学习。 提前致谢!
【问题讨论】:
标签: backbone.js marionette backbone-views backbone-model