jQuery UI datepicker change event not caught by KnockoutJS

后端 未结 13 2483
长发绾君心
长发绾君心 2020-11-22 16:16

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 th

13条回答
  •  生来不讨喜
    2020-11-22 16:28

    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 inputs 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:

    KO.bindingHandlers.boundData = {
      init: function(element, __, allBindings) {
        element.boundData = allBindings.get('boundData');
      }
    };
    

    Use the binding to attcah the observable used for the input's value:

    
    

    And finally, when initializing the datepicker, use it's onSelect option:

    $('.my-date-input').datepicker({
      onSelect: function(dateText) {
        this.myObservable(dateText);
      }
      //Other options
    });
    

    This way, every time a user changes the date with the datepicker, the corresponding Knockout observable is also updated.

提交回复
热议问题