我的Backbone模型中存在范围问题。我试图引用Backbone.Validation对象中的模型函数。
即,我无法从goto
对象/地图中访问模型函数validateDob
:
validation
我可以建议如何设置它?
答案 0 :(得分:1)
查看您的代码,validateDob
并不需要访问该实例,因此您可以按如下方式将其命名为命名函数:
function validateDob(value) {
var selDay = $('select[name="dobday"] option:selected').val();
var selMonth = $('select[name="dobmonth"] option:selected').val();
var selYear = $('select[name="dobyear"] option:selected').val();
if (!Utils.isAdult(selDay, selMonth, selYear))
return _('You have to be at least 18 years old.').translate();
}
Backbone.Model.extend({
validation: {
firstname: {
required: true,
msg: _('First Name is required').translate()
},
dobday: validateDob,
dobmonth: validateDob,
dobyear: validateDob
},
validateDob: validateDob
});
但是,不建议使用全局选择器直接从DOM访问值。您应该使用作用于视图元素的选择器将这些值设置为模态属性。
在这种情况下,假设您使用backbone.validation插件,您可以定义一个返回验证配置的函数,如:
Backbone.Model.extend({
validation: function() {
return {
firstname: {
required: true,
msg: _('First Name is required').translate()
},
dobday: this.validateDob, // this should be modal instance now
dobmonth: this.validateDob,
dobyear: this.validateDob
}
},
validateDob: function(value) {
// Now context should be the modal instance so you can do this.get('prop')
var selDay = $('select[name="dobday"] option:selected').val();
var selMonth = $('select[name="dobmonth"] option:selected').val();
var selYear = $('select[name="dobyear"] option:selected').val();
if (!Utils.isAdult(selDay, selMonth, selYear))
return _('You have to be at least 18 years old.').translate();
}
});
答案 1 :(得分:0)
你可以试试这个
Backbone.Model.extend({
validation: {
firstname: { required: true, msg: _('First Name is required').translate() }
},
initialize:function() {
this.validation.dobyear= this.validateDob;
//you can other props similarly
},
validateDob: function(value) {
var selDay = $('select[name="dobday"] option:selected').val();
var selMonth = $('select[name="dobmonth"] option:selected').val();
var selYear = $('select[name="dobyear"] option:selected').val();
if (!Utils.isAdult(selDay, selMonth, selYear))
return _('You have to be at least 18 years old.').translate();
}
});