MichaelK
MichaelK

Reputation: 832

invalid date when using knockout.js and moment.js

I'm using Knockout in combination with moment.js and C#. In C# i pass in a ISO formatted date by using: var jsonString = JsonConvert.SerializeObject(dataObject}, new IsoDateTimeConverter());

In my HTML file i'm doing the following to display my date in a formatted way:

<script type="text/javascript">
var viewModel = {};
$.getJSON("http://www.test.com/jsonfile.txt", function(data) { 
viewModel.model = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
</script>
<div>Hello</div>
<div>Time: <span data-bind="text: moment(model.Time).format('L')"></span></div>

I always get Invalid date but when i use:

<div>Time: <span data-bind="text: model.Time"></span></div>

it just displays correctly Time: 2014-08-25T09:49:00

Anyone an idea what i'm doing wrong?

Upvotes: 2

Views: 4989

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075219

fromJS creates observables, so model.Time is a function. So:

<span data-bind="text: moment(model.Time()).format('L')"></span>
<!-- Change is here --------------------^^                   -->

But the KO way would probably be to create a computed observable for that:

<script type="text/javascript">
var viewModel = {};
$.getJSON("http://www.test.com/jsonfile.txt", function(data) { 
    viewModel.model = ko.mapping.fromJS(data);
    viewModel.model.FormattedTime = ko.computed(function() {
        return moment(viewModel.model.Time()).format('L');
    });
    ko.applyBindings(viewModel);
});
</script>
<div>Hello</div>
<div>Time: <span data-bind="text: model.FormattedTime"></span></div>

Or better yet, your own binding: Live Example

ko.bindingHandlers.formattedTime = {
  update: function(element, valueAccessor) {
    $(element).text(moment(ko.unwrap(valueAccessor())).format('L'));
  }
};

Then:

<div>Time: <span data-bind="formattedTime: model.Time"></span></div>

Upvotes: 7

Related Questions