super cool
super cool

Reputation: 6045

Observable not getting Refreshed on Submit ? knockoutjs(Fiddle Provided)

Well i have a scenario where my selected date from TextBox is displaying wrong on change of date(datepicker) in textbox in my alert window on my submit button click .

On-initial button click you can see the output in alert but later if you change date you will get same date what you got in the 1st instance. observable is not getting refreshed

Fiddle link : : http://jsfiddle.net/JL26Z/24/

Any workaround is much appreciated

Upvotes: 0

Views: 310

Answers (2)

Ilya Luzyanin
Ilya Luzyanin

Reputation: 8110

The main issue you have is that you're not adding any callback to value changes, so there is no way knockout will update the observable - because the value inside it doesn't change. Below is my datepicker binding handler I used some time ago in one of my projects. It's small and very simple, but should do the job:

(function ($, ko) {
    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            // initialize datePicker with options (not required)
            var options = allBindingsAccessor().datepickerOptions || {};
            $(element).datepicker(options);

            // change date handler
            ko.utils.registerEventHandler(element, "change", function () {
                var observable = valueAccessor();
                observable($(element).datepicker("getDate"));
            });
        },
        update: function (element, valueAccessor) {
            // update date value
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).datepicker("setDate", value);
        }
    }
})(jQuery, ko);

Important note: it works with dates, not strings. So in your view model you should use dates, like this:

...
self.Date = ko.observable(new Date('2014-06-03T00:00:00'));//before formatting
...

And the markup now should look like this:

<input type="text" data-bind="datepicker: Date"  />

You could also add datepicker options like this:

<input type="text" data-bind="datepicker: Date, datepickerOptions: {...}"  />

Here is full working demo.

Upvotes: 1

Nazar Harasym
Nazar Harasym

Reputation: 43

You are trying to get date from observable function, not array

Try this.

It will show you time

alert(self.PhoneList()[0].Date());

In this case we are getting array from observable array and showing first item Date property

Upvotes: 0

Related Questions