Search code examples
javascriptfunctionmethodspikaday

JavaScript: how to retrieve value from a method that doesn't have `return`


I am trying to modify an existing datepicker plug-in (Pikaday) to display the selected date in some rendered HTML (that is rendered in the plugin).

I have identified that the following setDate method/function returns the date string I want to use, but I am unsure how to extract it and use it in my function.

The setDate method appears as:

 setDate: function(date, preventOnSelect)
    {
        if (!date) {
            this._d = null;

            if (this._o.field) {
                this._o.field.value = '';
                fireEvent(this._o.field, 'change', { firedBy: this });
            }

            return this.draw();
        }
        if (typeof date === 'string') {
            date = new Date(Date.parse(date));
        }
        if (!isDate(date)) {
            return;
        }

        var min = this._o.minDate,
            max = this._o.maxDate;

        if (isDate(min) && date < min) {
            date = min;
        } else if (isDate(max) && date > max) {
            date = max;
        }

        this._d = new Date(date.getTime());
        setToStartOfDay(this._d);
        this.gotoDate(this._d);

        if (this._o.field) {
            this._o.field.value = this.toString();
            fireEvent(this._o.field, 'change', { firedBy: this });
            //I want to return `this._o.field.value`
        }
        if (!preventOnSelect && typeof this._o.onSelect === 'function') {
            this._o.onSelect.call(this, this.getDate());
        }
    }

and I want to return this._o.field.value.

Would anyone know how I could grab this and use it in my function?

PS, I am coming from a PHP OOP background, so my understanding of JS OOP might be lacking, sorry. My HTML rendering function:

renderHeading = function(instance, c, year, month, days)
{
    var opts = instance._o;
    var html = '<div class="pika-heading">';
    html += '<h3 class="pika-heading-year">' + year + '</h3>';
    html += '<h1 class="pika-heading-date">' + opts.i18n.weekdaysShort[day] + ', ' + opts.i18n.monthsShort[month] + '</h1>';
    return html += '</div>';
}

Solution

  • if (this._o.field) {
                this._o.field.value = this.toString();
                window.myDateProperty = this._o.field.value;// Add your own property
                fireEvent(this._o.field, 'change', { firedBy: this });
                //I want to return `this._o.field.value`-- I wont prefer returning as that alters the library code.
            }
    

    now window.myDateProperty containing the this._o.field.value will be available in the javascript files.

    PS: always do the check:

    if(window.myDateProperty){
      //use window.myDateProperty
    }