2014-09-12 70 views
1

我所有的日期都會從後端格式化爲ISO 8601,例如2014-01-01T12:45:30Z。整個應用程序,我想在不同的格式來顯示他們......在表格式化Can.js中顯示的日期值

  • 簡寫,如Jan 1
  • 更長的時間,進行了詳細的視圖更明確的格式,如Monday, January 1st

解決方案我做了一個幫手,我可以通過格式。很簡單。

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

問題現在我實現bootstrap datepicker,我如何能捕捉這些要求......

  • 在我的模型日期被格式化爲ISO
  • 綁定輸入與can-value in template
  • display format MM/DD/YY for users and datepicker

獎勵積分如果我不需要爲我的模型中的每個日期值創建一個compute,因爲它們非常大且有很多日期。

回答

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格式也會保存到服務器)。

有一些關於添加過濾器/解析器的內部討論,以允許控制僅用於查看呈現的格式。

+0

謝謝!我很高興聽到團隊正在考慮提供該功能。 – 2014-09-12 19:56:17

+0

你能解釋這一點嗎? 'value = data.scope.computeData(attr,{args:[]})。compute;' – 2014-09-12 20:03:48

+0

@SpencerAvinger這就是我們如何找到綁定到輸入的實際計算。 http://canjs.com/docs/can.view.Scope.computeData.html – 2014-09-16 19:00:11