我正在努力使用主干创建一个验证 View ,该 View 将处理给定输入上样式气球中验证消息的显示。我创建了一个处理此功能的新 View 。为了执行验证并渲染 View ,我在模型中设置了以下函数。
Dashboard.Models.EventModel = Backbone.Model.extend({
idAttribute: "Id",
// Model Service Url
url: function () {
var base = 'apps/dashboard/EventsDetails';
return (this.isNew()) ? base : base + "/" + this.id;
},
validate: function (attrs) {
var validTime = (attrs.Time) ? attrs.Time.match(/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/) : true;
if (!validTime) {
new Dashboard.Views.ValidationMessageView({
$container: $('#txtNewEventTime'),
message: 'Invalid Time'
}).render();
return 'error';
};
}
});
我的问题:创建新 View (ValidationMessageView) 并从模型中渲染它是否违反标准?
最佳答案
恕我直言:是的!..它看起来不太好。
您应该在Model
外部实例化View
。
您应该在模型中绑定(bind)事件 错误
,从外部捕获它并在那里实例化ErrorView
.
检查the example in the Model.validate
documentation
很快你就可以拥有一个像这样的AllErrorsView
:
// code simplfied and not tested
var AllErrorsView = Backbone.View.extend({
initialize: function(){
this.model.on( "error", this.showError, this );
},
showError: function( model, error ){
if( error == "txt_new_event_time" ) {
new Dashboard.Views.ValidationMessageView({
el: "#txtNewEventTime",
message: "Invalid Time"
}).render();
}
// ... more errors
}
});
var myAllErrorsView = new AllErrorsView({ model: myModel });
我不得不说,这并不是我在你的代码中看到的唯一奇怪的事情。例如我不明白你的 Model.url
实现的含义,我认为你可以用 Model.urlRoot attribute 来解决它.
关于javascript - Backbone 模型验证标准(这样做有错吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334923/