I am getting “Uncaught ReferenceError: Cannot access ‘Q12’ before initialization” inside the changeCssClassIfOldAndNewValuesAreDifferent function. Any idea why? Thanks.
const formController = (function () {
return {
'changeCssClassIfOldAndNewValuesAreDifferent': changeCssClassIfOldAndNewValuesAreDifferent
};
const formScope: any = $("form#userAnswerForm");
const Q12: any = $('.persistable[id=Q12]', formScope);
const Q23: any = $('.persistable[id=Q23]', formScope);
function changeCssClassIfOldAndNewValuesAreDifferent() {
$('input.persistable, select.persistable').not(Q12) //<---Reference Error
.each(function () {
console.log('each persistable input and select listeners (change, mouseout)');
const thisPersistable: any = $(this);
const Q12_or_Q23_is_not_empty: boolean = !commonUtility.isEmpty(Q12) &&
!commonUtility.isEmpty(Q23);
...
...
});
}
})();
$(function(){
formController.changeCssClassIfOldAndNewValuesAreDifferent();
});
4
In short you just have to move declaration before return cause in return you call function that try access Q12 which is declared after return
const formController = (function () {
const formScope: any = $("form#userAnswerForm");
const Q12: any = $('.persistable[id=Q12]', formScope);
const Q23: any = $('.persistable[id=Q23]', formScope);
return {
'changeCssClassIfOldAndNewValuesAreDifferent': changeCssClassIfOldAndNewValuesAreDifferent
};
function changeCssClassIfOldAndNewValuesAreDifferent() {
$('input.persistable, select.persistable').not(Q12) //<---Reference Error
.each(function () {
console.log('each persistable input and select listeners (change, mouseout)');
const thisPersistable: any = $(this);
const Q12_or_Q23_is_not_empty: boolean = !commonUtility.isEmpty(Q12) &&
!commonUtility.isEmpty(Q23);
...
...
});
}
})();
$(function(){
formController.changeCssClassIfOldAndNewValuesAreDifferent();
});