JQuery doesn't locate DOM elements when using Durandal's compose

前端 未结 2 1475
情歌与酒
情歌与酒 2021-02-11 09:05

I\'ve recently ported my company\'s project to Durandal using Knockout and JQuery. Straight to the problem: I need to initialize JQuery UI\'s datepicker using two HTML inputs. J

相关标签:
2条回答
  • 2021-02-11 09:27

    Pretty sure the problem is with this:

    users.SelectUser = function (user) {
        servers.CurrentUser(user);
    
        /* ... */
    
        $(function () {
            $("#datepickerFrom").datetimepicker({
                dateFormat: "d. m. yy",
                timeFormat: "HH:mm:ss",
                defaultDate: null
            });
    
            $("#datepickerTo").datetimepicker({
                dateFormat: "d. m. yy",
                timeFormat: "HH:mm:ss"
            });
        });
    }
    

    You have your jQuery datepicker init code inside a function. That means that it will only run when the SelectUser function gets called. Try moving that outside of any functions.

    0 讨论(0)
  • 2021-02-11 09:29

    In this scenario you need a Knockout Binding Handler.

    In some scenarios the binding handlers can have issues with the Composition lifecycle, if thats the case and you are using Durandal 2 you can use the method composition.addBindingHandler. Otherwise just use ko.bindingHandlers.

    You will need to create the bindings in the shell.js or main.js so they are available in all the application. Use the following code:

     var composition = require('durandal/composition');
     composition.addBindingHandler('datetimepicker', {
                init: function (element, valueAccessor) {
                    var activeTo =  valueAccessor();  //What do you want to do with this value?
                    $(element).datetimepicker({
                       dateFormat: "d. m. yy",
                       timeFormat: "HH:mm:ss",
                       defaultDate: null   //Maybe use activeTo here?
                      });
                }
             });
    

    And in your UI:

     <input type="text" data-bind="datetimepicker: ActiveTo" id="datepickerTo" />
    

    NOTE:

    This code might not work, but you should definitely use this approach to create this kind of controls and use Durandal's composition lifecycle.

    0 讨论(0)
提交回复
热议问题