Observable not getting Refreshed on Submit ? knock

2019-08-17 05:24发布

问题:

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

回答1:

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.



回答2:

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



标签: knockout.js