Backbone ModelBinder and jQuery Plugin



在使用Backbone&Marionette,我希望一些表单输入仅为数字,并带有数千分隔符。Backbone ModelBinder自动检测表单中的更改。我实现了jQuery数字插件,它运行良好。但问题是,当数字输入中有一个千分隔符时,ModelBinder就不起作用了。当数字少于4位时(没有分隔符),一切正常。

问题出现在Chrome上。Firefox没有任何问题。

我不知道如何解决或调试这个问题。

将两者结合在一起会带来麻烦:模型绑定器在输入更改时触发更改事件,并将字段数据转发给模型。只是它被数字插件篡改了,所以出现了问题。

请尝试使用ModelBinder的转换器绑定设置(https://github.com/theironcook/Backbone.ModelBinder#formatting-以及转换值),它将允许您定义在从模型到表单再返回时应该如何格式化/解析数据。

使用ModelBinder的转换器,而不是jQuery插件。这里有一个示例,它清理时间(例如3p、3:00、3PM、15:00、1500等),如果输入可以解析,则以规范形式(ISO8601的时间部分)将数据存储在模型中,如果不能解析,则按原样存储,以便验证可以单独检查并提供错误。

当用户更改输入时,ModelBinder的转换器会被调用两次。首先,当输入数据从视图复制到模型direction === 'ViewToModel'时。这允许进行清理,并将输入值转换为适合存储的规范形式,例如在本例中为24小时带秒(15:30:00)。其次,从模型返回视图,direction === 'ModelToView',它允许您以友好的方式将数据呈现给用户,在本例中为12小时时间(3:30 PM)。

这个例子使用一个时间库来处理时间输入,解析它,并格式化它

绑定

在这种情况下,使用Backbone渲染视图后立即调用onRender。Marionette

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;
};

最新更新