Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use JQuery Datepicker with Backbone-Forms?

var User = Backbone.Model.extend({
    schema: {
        date: {type: 'Date'}
    }
});

var user = new User();

var form = new Backbone.Form({
    model: user
}).render();

$('.bootstrap').append(form.el);

What type do I enter to use the included JQuery-UI datepicker? There is no documentation on this other than:

The old jQuery editors are still included but may be moved to another repository:

jqueryui.List
jqueryui.Date (uses the jQuery UI popup datepicker)
jqueryui.DateTime

The schema type is declared in quotes and I can't figure out what the string for jqueryui.Date would be - and that doesn't work for sure.

like image 487
Adrian Bartholomew Avatar asked Jan 14 '23 12:01

Adrian Bartholomew


1 Answers

You want to create a custom editor that you'll name for example: 'DatePicker'.

All the editors are attached to Backbone.Form.editors. Because the DatePicker is rendered exactly like a text field, we can use the text field as a base and only override the behavior specific to the datepicker.

I often use moment.js for some date related work, so this example also includes this. Also it's based on Bootstrap DatePicker and not the jQuery one, but this would be almost 100% the same.

Backbone.Form.editors.DatePicker = Backbone.Form.editors.Text.extend({
    render: function() {
        // Call the parent's render method
        Backbone.Form.editors.Text.prototype.render.call(this);
        // Then make the editor's element a datepicker.
        this.$el.datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            weekStart: 1
        });

        return this;
    },

    // The set value must correctl
    setValue: function(value) {
        this.$el.val(moment(value).format('YYYY-MM-DD'));
    }
});

That's it, you can now use your date picker like this:

schema: {
    birthday: { title: 'When were you born', type: 'DatePicker'}
}
like image 107
Khepin Avatar answered Feb 04 '23 11:02

Khepin