1

I'm trying to use Knockout computed to concatenate two dates as I change them.
From the examples, it seems I do not need to use valueUpdate: 'input'. But nothing is happening when I change the dates (using Bootstrap datepicker). Any ideas to what I'm missing?

Here's my fiddle.

And my code:

<div class="input-append date">
    <input type="text" data-bind="value: fromDate, valueUpdate: 'input'" class="date from-date" /> 
    <span class="add-on">to</span>
    <input type="text" data-bind="value: toDate, valueUpdate: 'input'" class="date to-date" />
</div>
Dato: <span class="date" data-bind="date"></span>


function dateModel() {
    var self = this;
    self.fromDate = ko.observable('12.09.2014');
    self.toDate = ko.observable();

    self.validPeriod = ko.computed(function () {
        return self.fromDate + " - " + self.toDate;
    }, self);
}

ko.applyBindings(dateModel());
Steven
  • 19,224
  • 47
  • 152
  • 257
  • So you want to output: `12.09.2014 - 13.09.2014` if `fromDate` is `12.09.2014` and `toDate` is `13.09.2014`? – keenthinker May 25 '14 at 17:16
  • Actually I want to output something like `12-13 sep 2014`. But how the output looks is not important now. – Steven May 25 '14 at 17:46

1 Answers1

2

Because your date picker objects are of type koObservable, you need to treat the objects as functions, so your validPeriod function should look like:

self.validPeriod = ko.computed(function () {
    return self.fromDate() + " - " + self.toDate();
}, self);

The Knockout.js documentation for observables states:

To read the observable’s current value, just call the observable with no parameters. In this example, myViewModel.personName() will return 'Bob', and myViewModel.personAge() will return 123.

Then i would suggest using the text data binding for the date span element to call the calculation function:

<span class="date" data-bind="text: validPeriod"></span>

Thanks to the comment of @Buck Doyle and some research, it seems that Knockout.js needs special handling regarding datetime picker controls, as showed in this SO post - jQuery UI datetimepicker and Knockout.js - one possible solution to your problem would be to implement the custom datetime picker handling for KOjs.

This page - custom bindings with KOjs explains very good (with example) how to bind the datetime picker control.

Community
  • 1
  • 1
keenthinker
  • 7,645
  • 2
  • 35
  • 45
  • 2
    This isn’t enough for this example, sadly, though it does address some problems. The `datepicker` elements don’t trigger the right events for the computed property to be updated when they change. If you type in the field manually, it works, but not if you use the datepicker. [This answer](http://stackoverflow.com/a/6613255/760389) would help with that, though. – Buck Doyle May 25 '14 at 17:24
  • 1
    Ok, thanks. I think I'll just use normal jQuery. It'll be way less code :-/ – Steven May 25 '14 at 18:05