ragdollpanda
ragdollpanda

Reputation: 23

Knockout.js - How to modify an observable JS Date object?

I have a ko.observable handling a JS Date object like so:

vm.date = ko.observable(new Date());

I need a simple function that can increase or decrease the date by x days. Like so:

vm.changeDay = function(x) {
  // I want this function to increase or decrease date by x days each time it is called.
};

The problem with my current implementations have been that the vm.date observable would not update in my View. This is probably because a JS Date object is more than a simple string, and need to be broken apart and put together in a specific way in order to be observable. I tried using ko.computed to do this, but did not succeed.

See jsfiddle for a simple overview of the problem: http://jsfiddle.net/tp6jb4x1/

Upvotes: 2

Views: 340

Answers (2)

Milimetric
Milimetric

Reputation: 13549

The date logic was a little un-obvious so I updated your fiddle:

http://jsfiddle.net/tp6jb4x1/3

Relevant part:

... data-bind="click: changeDay.bind($data, 1)" ...

self.changeDay = function(dayDelta) {
    var d = this.date();
    d.setDate(d.getDate() + dayDelta);
    this.date(new Date(d.getTime()));
};

Your approach with a computable might have been working but the date logic might have been wrong. I like using writeable computed observables instead of more complicated function calls wherever I can.

Upvotes: 0

Wheeler
Wheeler

Reputation: 296

You can pass your parameters in KO like this:

<button data-bind="click: changeDay.bind($data,'-1')">Prev day</button>
<button data-bind="click: changeDay.bind($data,'1')">Next day</button>

see ref: Passing parameter using onclick or a click binding with KnockoutJS

Upvotes: 2

Related Questions