Javascript 主干ModelBinder和jQuery插件

Javascript 主干ModelBinder和jQuery插件,javascript,jquery,backbone.js,marionette,Javascript,Jquery,Backbone.js,Marionette,在一个用主干线和木偶线编写的应用程序中,我希望一些表单输入仅为数字且带有数千分隔符。主干ModelBinder自动检测表单中的更改。我实现了一个很好的方法。但问题是,当一个数字输入中有数千个分隔符时,ModelBinder就不起作用了。如果少于4位(没有分隔符),则一切正常 问题发生在Chrome上。Firefox上没有任何问题 我不知道如何解决或调试这个问题。您将这两种方法结合起来是在自找麻烦:当输入发生更改时,model binder会触发更改事件,并将字段数据转发到模型。除了它被数字插件篡

在一个用主干线和木偶线编写的应用程序中,我希望一些表单输入仅为数字且带有数千分隔符。主干ModelBinder自动检测表单中的更改。我实现了一个很好的方法。但问题是,当一个数字输入中有数千个分隔符时,ModelBinder就不起作用了。如果少于4位(没有分隔符),则一切正常

问题发生在Chrome上。Firefox上没有任何问题


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

您将这两种方法结合起来是在自找麻烦:当输入发生更改时,model binder会触发更改事件,并将字段数据转发到模型。除了它被数字插件篡改之外,因此会出现问题


相反,请尝试使用ModelBinder的转换器绑定设置(),它将允许您定义数据在从模型到表单再到表单时的格式/解析方式。

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

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

本例使用一个函数来操作时间输入、解析它并格式化它

绑定

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

转换器

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

我的猜测是,当有人提交时,您需要对输入进行清理(以删除分隔符)。但如果没有任何代码,则很难判断在何处执行此操作。我假设在数据保存到的模型中,或者在负责表单的视图中。
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;
  };