moment 和ko 绑定msdate格式的日期值(静态text)

时间:2021-06-25 22:09:37
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" /> <script src="moment-with-locales.min.js"></script>
<script src="knockout-3.1.0.js"></script>
<script src="jquery-1.10.2.js"></script> </head>
<body> <div data-bind="msDateText: date" ></div>
<!-- 带指定格式方式-->
<div data-bind="msDateText: date,format:'llll'"></div>
</body> <script>
// moment().format();
moment.locale('zh-cn'); var myViewModel = {
date:ko.observable("/Date(1198908717056-0700)/")
}; ko.bindingHandlers.msDateText = { /*
只绑定div之类的text,不需要init,其实写在init也可以
*/
update: function(element, valueAccessor,allBindings) {
//valueAccessor是ko绑定模式,需要解一下
var value = ko.utils.unwrapObservable(valueAccessor());
var showText ;
//获得format参数
if (allBindings.has('format'))
{
var format = allBindings.get('format');
showText = moment(value).format(format);
}
else
{
showText = moment(value)
}
$(element).text(showText);
}
};
ko.applyBindings(myViewModel); </script>
</html>