Question

I have a widget that basically creates a JQuery datepicker on an element and then handles the retrieval of data from a web service and the enabling/disabling of dates based on the data returned.

The widget gets defined like this - a few simple default options:

$.widget("XXXX.CalendarBooking", {
    options: {
    minDaysInAdvance: 0,
    maxDaysInAdvance: 0,
    productNumber: '',
    url: '',
    numberOfDays: 40
},
...

The constructor looks like this, where it creates the datepicker on the element, and then sets up the functions for retrieving data and processing (enabling) dates:

_create: function () {
    this.element.datepicker({
        dateFormat: 'dd MM yy',
        firstDay: 1,
        minDate: this.options.minDaysInAdvance,
        maxDate: this.options.maxDaysInAdvance,
        beforeShowDay: this._processDate,
        onChangeMonthYear: this._changeMonthYear
    });
    ...

The processdate function looks like this:

_processDate: function (date) {
    // get availability
    if (!this._availability) {
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: this.options.url,
        data: '{ productNumber: "' + this.options.productNumber + '", startDate: "' + date.toJSON() + '", numberOfDays: ' + numberOfDays + ' }',
        dataType: "json",
        success: function (msg) {
            _setAvailability(msg.d);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            _setAvailability('error');
        }
    });
}

However, when processdate gets called, the context is not within the widget, so I don't have access to the options. Am I doing this right, or is there a way to overload the processdate function, so that when setting the callback for beforeShowDay, I can pass in the options, and it won't overwrite the date value that JQuery will pass to that function?

Was it helpful?

Solution

You can use $.proxy to set the context within which a function should be called. try this:

beforeShowDay: $.proxy(this._processDate, this),

Now, within your _processDate function the this keyword will refer to your widget. You can get access to the element the event was raised on using this.element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top