使用 jquery-ui 日期选择器进行淘汰赛数据绑定 [英] knockoutjs databind with jquery-ui datepicker

查看:25
本文介绍了使用 jquery-ui 日期选择器进行淘汰赛数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery UI 日期选择器.它背后的 HTML 输入字段目前被连接到 KnockoutJS 作为一个依赖的Observable,但是当它的值在视图模型中设置时,日期选择器丢失其格式.

I'm using a jQuery UI datepicker. The HTML input field behind it is currently hooked up to KnockoutJS as a dependentObservable, but when its value is set in the viewmodel, the datepicker loses its format.

我应该如何做到这一点而不丢失格式?我希望 viewModel 不知道它是一个 jQuery 日期选择器.

How should I do this and not lose the format? I would like the viewModel not to know that it is a jQuery datepicker.

推荐答案

您可以编写一个自定义绑定,使用 datepicker API 在字段中设置日期,并通过正确读取日期来设置您的 observable 的值.

You could write a custom binding that sets the date in the field using the datepicker APIs and also sets the value of your observable by reading the date properly.

>

自定义绑定可能如下所示:

The custom binding might look like:

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().datepickerOptions || {},
            $el = $(element);

        //initialize datepicker with some optional options
        $el.datepicker(options);

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

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

    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $el = $(element),
            current = $el.datepicker("getDate");

        if (value - current !== 0) {
            $el.datepicker("setDate", value);   
        }
    }
};

你会像这样使用它:

<input data-bind="datepicker: myDate, datepickerOptions: { minDate: new Date() }" />

datepickeroptions 是可选的,可以包含您想要传递到 datepicker() 调用中的任何内容.

The datepickeroptions would be optional and could include anything that you want to pass into the datepicker() call.

此外,这假设您使用的是日期的 observable.如果您想对不可观察对象进行单向绑定,则绑定必须做更多的工作,但这不太可能.

Also, this assumes that you are using an observable for the date. The binding has to do a little more work if you want to do a one-way binding with a non-observable, but that is unlikely.

示例:http://jsfiddle.net/rniemeyer/NAgNV/

这篇关于使用 jquery-ui 日期选择器进行淘汰赛数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆