[英]Backbone ModelBinder and jQuery Plugin
在用Backbone&Marionette编写的应用程序中,我希望某些表单输入仅作为数字并带有千位分隔符。 Backbone ModelBinder自动检测表单中的更改。 我实现了很好的jQuery数字插件 。 但是问题在于,当数字输入中包含数千个分隔符时,ModelBinder无法正常工作。 如果少于4位数字(不带分隔符,则表示一切正常)。
该问题在Chrome上出现。 在Firefox上没有任何问题。
我不知道如何解决或调试问题。
您需要通过将两者结合来解决问题:当输入发生更改时,模型绑定器会触发更改事件,并将字段数据转发至模型。 除非它已被数字插件篡改,否则会出现问题。
相反,请尝试使用ModelBinder的转换器绑定设置( https://github.com/theironcook/Backbone.ModelBinder#formatting-and-converting-values ),它将允许您定义从模型中获取数据时应如何格式化/解析到表格并返回。
为此,请使用ModelBinder的转换器,而不要使用jQuery插件。 这是清理时间(例如3p,3:00、3PM,15:00、1500等)的示例,如果可以解析输入,则以规范形式(ISO8601的时间部分)将数据存储在模型中,如果没有,则按原样存储,以便验证可以单独检查它并提供错误。
用户更改输入时,ModelBinder的转换器被调用两次。 首先,将输入数据从视图复制到模型时, direction === 'ViewToModel'
。 这样可以进行清理,并将输入值转换为适合存储的规范形式,例如,在本示例中为24小时制,秒为( 15:30:00
)。 其次,从模型返回到视图, direction === 'ModelToView'
,在此示例中,它允许您以友好的方式向用户展示数据,时间为12小时( 3:30 PM
)。
本示例使用时间库来操纵时间输入,对其进行解析并对其进行格式化。
捆绑
在这种情况下,在使用Backbone.Marionette渲染视图之后立即调用onRender
onRender: function() {
var bindings = ModelBinder.createDefaultBindings(this.$el, 'name');
bindings.value.converter = ModelSaver.timeStringConverter;
this.modelbinder.bind(this.model, this.$el, bindings);
}
变流器
ModelSaver.timeStringConverter = function(direction, value, attributeName, model, els) {
var result;
if (direction === 'ViewToModel') {
if (!value)
// if the input is empty, just pass it along so it can be deleted, and/or validation can indicate it was a required field
result = value;
else {
// parse the input value and store it with the second component only if it's valid, if not, store the invalid value so that model validation can catch it
result = new Time(value);
result = result.isValid() ? result.format('HH:mm')+':00' : value;
}
}
if (direction === 'ModelToView') {
// chop off the seconds, parse, check for validity, and format
result = value && new Time(value.substr(0,5));
result = (value && result.isValid()) ? result.format('h:mm AM') : value;
}
return result;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.