在使用主干& Marionette编写的应用程序中,我希望一些表单输入仅为数字形式,并带有数千个分隔符。主干ModelBinder自动检测表单中的更改。我实现了jQuery数插件,它工作得很好。但问题是,当一个数字输入中有数千个分隔符时,ModelBinder就不能工作。当小于4位数时(没有分隔符),一切正常。
这个问题发生在Chrome上。火狐没有任何问题。
我不知道如何解决或调试这个问题。
发布于 2013-12-31 08:49:27
通过将这两种方法结合在一起,您就会自找麻烦:当输入发生变化时,模型绑定器会触发更改事件,并将字段数据转发给模型。除了它被数字插件篡改了,所以问题就出现了。
相反,尝试使用ModelBinder的转换器绑定设置(https://github.com/theironcook/Backbone.ModelBinder#formatting-and-converting-values),它将允许您定义在从模型到表单和返回时应该如何格式化/解析数据。
发布于 2014-01-08 21:07:01
使用ModelBinder的转换器来代替jQuery插件。下面是一个示例,用于清理时间(例如3p、3:00、3 3PM、15:00、1500等),如果可以解析输入,则以规范形式(ISO8601的时间部分)将数据存储在模型中,如果输入不能解析,则按原样存储,以便验证可以单独检查数据并提供错误。
当用户更改输入时,ModelBinder的转换器会被调用两次。首先,当输入数据从视图复制到模型时,direction === 'ViewToModel'。这允许进行清理,并将输入值转换为适合存储的规范形式,例如,在本例中的24小时时间内(15:30:00)。其次,从模型返回到视图direction === 'ModelToView',它允许您以友好的方式在本例中的12小时时间(3:30 PM)中向用户显示数据。
这个例子使用一个时间库来操作时间输入,解析它并格式化它。
结合
在本例中,onRender是在视图使用Backbone.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;
};https://stackoverflow.com/questions/20854374
复制相似问题