不幸的是,這還沒有一個很好的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格式也會保存到服務器)。
有一些關於添加過濾器/解析器的內部討論,以允許控制僅用於查看呈現的格式。
謝謝!我很高興聽到團隊正在考慮提供該功能。 – 2014-09-12 19:56:17
你能解釋這一點嗎? 'value = data.scope.computeData(attr,{args:[]})。compute;' – 2014-09-12 20:03:48
@SpencerAvinger這就是我們如何找到綁定到輸入的實際計算。 http://canjs.com/docs/can.view.Scope.computeData.html – 2014-09-16 19:00:11