格式化在Can.js中显示的日期值

时间:2014-09-12 19:24:37

标签: canjs canjs-view

我的所有日​​期都从后端格式化为ISO 8601,例如2014-01-01T12:45:30Z。在整个应用程序中,我想以不同的格式显示它们......

  • 表格中的简写,例如Jan 1
  • 详细视图中更长,更明确的格式,例如Monday, January 1st

解决方案我做了一个帮助,我可以传递格式。很容易。

can.mustache.registerHelper('formatDate', function(date, format) {
    return date() ? moment(date()).format(format) : '-';
});

问题现在我正在实施bootstrap datepicker,我该如何捕捉这些要求......

  • 我的模型中的日期格式为ISO
  • 使用模板
  • 中的can-value绑定到输入
  • 用户和datepicker的显示格式 MM / DD / YY

加分如果我不需要为模型中的每个日期值设置compute,因为它们非常大并且有很多日期。

1 个答案:

答案 0 :(得分:1)

不幸的是,没有一个很好的API(尚未)。但是,您可以在视图中实现自定义格式,同时使用以下代码保持模型属性的原始状态。

can.view.attr('can-somecustom-value', function(el, data) {
  var attr = el.getAttribute('can-somecustom-value'),
  value = data.scope.computeData(attr, {
    args: []
  }).compute;

  new FormattedValue(el, {
    value: value
    //value is the only one we really care about, but
    //you could specify other arbitrary options here
    //such as "format: 'MM/DD/YYYY' to be used in your __format methods below"
  });
});

var FormattedValue = can.Control.extend({
  init: function () {
    this.set();
  },

  __format: function() {
    // return formatted version of this.options.value;
  },

  __deformat: function() {
    // return this.element[0].value sans format(keeps your model pristine);
  },

  '{value} change': 'set',
  set: function () {
    if (!this.element) {
      return;
    }

    var self = this;

    setTimeout(function() {
      self.element[0].value = self.__format();
    });
  },

  'change': function () {
    if (!this.element) {
      return;
    }

    this.options.value(this.__deformat());
  }
});

这将允许您执行以下操作:

<input can-somecustome-value="myDateProp"/>

其中“myDateProp”是某些can.Map /can.Model / etc的属性。

这将导致输入显示自定义字符串格式,而someModel.attr('myDateProp')仍将返回ISO格式(这反过来意味着ISO格式也将保存到服务器)。

有一些关于添加过滤器/解析器的内部讨论,以允许控制仅针对视图呈现的格式。