Jquery UI datepicker使用Knockoutjs,ASP.Net中的momentjs

时间:2013-12-02 03:54:21

标签: jquery jquery-ui knockout.js datepicker momentjs

我正在使用Niemeyer的自定义绑定。使用日期选择器选择日期时遇到问题。它显示当前日期,而不是输入标记中设置的日期。

我在某些方面错过了一些不太确定的小东西。

请纠正我,并帮助我继续前进。

请在以下位置查看jsfiddle: http://jsfiddle.net/q46aw/3/

HTML

         <div class="page">
           <div data-bind="with: person">
             <input data-bind="datepicker:fromDate, value:fromDate, datepickerOptions: {'dateFormat': 'mm-dd-yyyy' }" id="txtFromDate" />
           </div> 
         <span data-bind="text:person.fromDate"></span>
        </div>

的Javascript

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

        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {};
        $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);
        }
    }
};
$(function () {
    var demo = demo || {};
    //Constructor for a Person object
    demo.TY = function () {
        this.fromDate = ko.observable();
    }
    demo.viewmodel = (function () {
        //private
        var fromDateJSON = 'Date(1293858000000)';
        var person = new demo.TY()

            .fromDate(moment(fromDateJSON).format('MM-DD-YYYY'))

        //public
        return {
            person: person
        }
    })();
    //hookup knockout to our viewmodel
    ko.applyBindings(demo.viewmodel);
});

先谢谢, 拉朱

1 个答案:

答案 0 :(得分:0)

您的代码有两个问题:

  1. 您将日期选择器绑定到fromDate两次(datepicker: fromDate + value: fromDate
  2. 您的日期格式不正确,您可以使用mm-dd-yy代替mm-dd-yyyy(请参阅http://api.jqueryui.com/datepicker/#utility-formatDate
  3. 你可以在这里试试: http://jsfiddle.net/m7f4z/