knockout js: The “with” binding breaks the jquery

2019-08-08 21:17发布

问题:

http://jsfiddle.net/AYPze/9/

In this example I have two similar divs with the same goal. Bind the selected date from the datetimepicker and save it to the object binded by knockout js.

The problem with the first div is that the datetimepicker won't show up because i use the knockout "with" binding.

The second div uses the normal knockout js binding syntax, which works fine with the datetimepicker.

I experienced this behavior also with the jquery-ui Accordion

My Questions: Is this a bug in knockout or jquery-ui? Is there a work around, so I can use the "with" binding?

回答1:

Your problem is related to the with binding, but not in the way you think.

The problem you have is that the with binding in this case will remove the jQuery datepicker from the DOM element and that is why you don't see the datepicker for the first textbox.

The main problem here is that you are breaking a very important rule when working with Knockout and the DOM. You shouldn't access the DOM directly with jQuery like you are doing now. You have to use a bindingHandler to bridge the gap between your data model and the DOM model.

The Binding Handlers seem complex at first, but they are pretty handy once you get to know them.

Here is an updated version of your fiddle with a working datepicker: http://jsfiddle.net/AYPze/10/