I'm trying to use KnockoutJS with jQuery UI. I have an input element with a datepicker attached. I'm currently running knockout.debug.1.2.1.js
and it seems that the change event is never being caught by Knockout. The element looks like this:
<input type="text" class="date" data-bind="value: RedemptionExpiration"/>
I've even tried changing the valueUpdate
event type but to no avail. It seems like Chrome causes a focus
event just before it changes the value, but IE doesn't.
Is there some Knockout method that "rebinds all the bindings"? I technically only need the value changed before I send it back to the server. So I could live with that kind of workaround.
I think the problem's the datepicker's fault, but I can't figure out how to fix this.
Any ideas?
I think that for the jQuery UI datepicker it is preferable to use a custom binding that will read/write with Date objects using the APIs provided by the datepicker.
The binding might look like (from my answer here):
You would use it like:
Sample in jsFiddle here: http://jsfiddle.net/rniemeyer/NAgNV/
Using custom bindings provided in previous answers is not always possible. Calling
$(element).datepicker(...)
takes some considerable time, and if you have, for example, a few dozens, or even hundreds of elements to call this method with, you have to do it "lazy", i.e. on demand.For example, the view model may be initialized, the
input
s being inserted into the DOM, but the corresponding datepickers will only be initialized when a user clicks them.So, here is my solution:
Add a custom binding that allows to attach arbitrary data to a node:
Use the binding to attcah the observable used for the
input
's value:And finally, when initializing the datepicker, use it's
onSelect
option:This way, every time a user changes the date with the datepicker, the corresponding Knockout observable is also updated.
I solved this problem by changing the order of my included script files:
I think it can be done much easier:
<input data-bind="value: myDate, datepicker: myDate, datepickerOptions: {}" />
So you do not need manual change handling in init function.
But in this case, your 'myDate' variable will get only visible value, not Date object.
Alternatively, you can specify this in binding:
Update:
Thanks for this article I found it very useful.
If you want the DatePicker to behave exactly like the JQuery UI default behaviour I recommend adding a blur on the element in the change event handler:
i.e.