سؤال

I've created a custom KnockoutJS binding to use with Bootstrap DateTimePicker. Here's a JSFiddle to show what I mean:

http://jsfiddle.net/dXGB3/7/

It works great, except for one very important detail: Say that, after choosing a date, the user deletes the date from the corresponding textbox. The "update" method does not fire, and the backing field still contains the previously selected date. The user's expectation, however, is that they are submitting a form with no date, but that expectation is not met. To see the problem: in the fiddle, click to view the datetime picker. Select a date. Then, wipe the text out of the textbox. The date is still displayed in the span.

I started crafting a solution, but it also has a problem, and I'm not sure I'm going about this the best way. My solution:

Potential solution fiddle: http://jsfiddle.net/NGwGb/1/

Wrap my custom binding to include the value binding. The good news: "value" is now called when the user wipes out the text. But, I only want to overwrite (wipe out) the backing date object value in the one case where the user wipes out the text in the field. So I added this code to the update method:

    if ($(element).find("input").val() == "")
        valueAccessor()(null);
    else {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).data("DateTimePicker").setValue(value);
    }

I think it's really ugly for me to pull the value from an element in the DOM (defeats the purpose of databinding), plus this code breaks the scenario of populating the form initially from a date object in the back end.

I'd love to have suggestions on the best way to allow the user to really wipe out the contents of the date field in the model when they wipe the text from the field.

Thanks...

-Ben

هل كانت مفيدة؟

المحلول

Bootstrap DateTimePicker have error event. From documentation:

Fires when Moment cannot parse the date or when the timepicker cannot change because of a disabledDates setting. Returns a Moment date object. The specific error can be found be using invalidAt(). For more information see Moment's docs.

So, when user deletes the date from the corresponding textbox or write incorrect date, this event will be called. You could add something like this to your init function:

    $(element).datetimepicker(options).on("dp.error", function (ev) {
        var observable = valueAccessor();
        console.log(ev.date.toString()); // only for debug.
        observable("");
    });
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top