Search code examples
javascriptjqueryscopeprototype

Javascript: Scope issues in object


I cannot access certain variables from a function. Here's what I got:

var PTP = function (properties) {
    this.errorsArray = []
}


PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation)
}


PTP.prototype.dateValidation = function() {
    var field = '#' + $(this)[0].id
    var that = this
    $(field).focusout(function(){
        var valid = form_validate_date($(field).val())
        var label = $('#date').siblings('label').children('.label-text').text()

        if (!valid) {
            that.errorsArray.push({
                'field': field,
                'fieldType': 'date',
                'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
            })
        }
    })
}

The issue is that I cannot access errorsArray.

I also tried passing a callback function as a parameter to dateValidation:

PTP.prototype.addError = function(errorObj) {
    this.errorsArray.push(errorObj)
}

Tried this way:

PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation(this.addError))
}

and also this way:

PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation.bind(this.addError))
}

but that screwed with the scope of this in dateValidation:

PTP.prototype.dateValidation = function(callback) {
    var field = '#' + $(this)[0].id
    var that = this
    $(field).focusout(function(){
        var valid = form_validate_date($(field).val())
        var label = $('#date').siblings('label').children('.label-text').text()

        if (!valid) {
            callback({
                'field': field,
                'fieldType': 'date',
                'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
            })
        }
    })
}

How can I get access to errorsArray?


Solution

  • Change $('input[data-widget-type="date"]').each(this.dateValidation)

    to

    $('input[data-widget-type="date"]').each(function(index, element) {
      this.dateValidation(element);
    }.bind(this));
    

    and then change PTP.prototype.dateValidation = function(callback) {

    to PTP.prototype.dateValidation = function(element) { now, inside dateValidation, this is your PTP object, and element is the jquery element from your each loop