Skip to content

Nonissue: Knockoutjs binding code for Timepicker #417

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
DrZim opened this issue Aug 26, 2012 · 0 comments
Open

Nonissue: Knockoutjs binding code for Timepicker #417

DrZim opened this issue Aug 26, 2012 · 0 comments

Comments

@DrZim
Copy link

DrZim commented Aug 26, 2012

Thought I could pass along code I used to bind your addon to controls using Knockoutjs. It's especially useful when binding to a template where the bound item doesn't exist initially.

Thanks

// inspired by http://stackoverflow.com/questions/6612705/knockout-with-jquery-ui-datepicker
// use in Knockoutjs <input data-bind="datetimepicker: myDate, datetimepickerOptions: { minDate: new Date() }" />
(function(window, $, undefined) {
    if( window.ko && $.timepicker )
    {
        ko.bindingHandlers.datetimepicker = {
            init: function(element, valueAccessor, allBindingsAccessor) {
                //initialize datetimepicker with some optional options
                var options = allBindingsAccessor().datetimepickerOptions || {};
                $(element).datetimepicker(options);

                //handle the field changing
                ko.utils.registerEventHandler(element, "change", function () {
                    var observable = valueAccessor();
                    observable($(element).datetimepicker("getDate"));
                });

                //handle disposal (if KO removes by the template binding)
                ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                    $(element).datetimepicker("destroy");
                });

            },
            update: function(element, valueAccessor) {
                var value = ko.utils.unwrapObservable(valueAccessor());

                //handle date data coming via json from Microsoft
                if (String(value).indexOf('/Date(') == 0) {
                    value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
                }

                current = $(element).datetimepicker("getDate");

                if (value - current !== 0) {
                    $(element).datetimepicker("setDate", value);
                }
            }
        };
    }
}(window, jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant