I am trying to define a class using Webpack and JS.
In the constructor I can access the data but after assigning the data to this.t
the this.t
is not having the data in future methods in the class. This is the class:
module.exports = class JoiCustomErrors {
constructor(t) {
this.t = t;
console.log(this.t); // the wanted object info
}
parser(errors) {
console.log(this.t); // undefined
return errors.map(err => {
err.message = ({
"string.base": `${this.t['This field is required']}`,
"string.min": `${this.t['Minimum']} ${err.context.limit} ${this.t['chars']}`,
"string.max": `${this.t['Maximum']} ${err.context.limit} ${this.t['chars']}`,
"any.empty": `${this.t['This field is required']}`,
"any.required": `${this.t['This field is required']}`,
"number.min": `${this.t['Should be greater than']} ${err.context.limit}`,
"number.max": `${this.t['Should be less than']} ${err.context.limit}`,
"number.base": `${this.t['Digits only']}`,
"date.base": `${this.t['Date format must be']} yyyy-mm-dd`,
"date.isoDate": `${this.t['Date format must be']} yyyy-mm-dd`,
"date.min": `${this.t['Should be later than']} ${err.context.limit}`,
"date.max": `${this.t['Should be earlier than']} ${err.context.limit}`,
"any.allowOnly": `${this.t['Unknown value']}`,
"array.max": `${this.t['Maximum']} ${err.context.limit} ${this.t['Items']}`,
"array.min": `${this.t['Minimum']} ${err.context.limit} ${this.t['Items']}`,
"array.includesRequiredUnknowns": `${this.t['Minimum']} 1 ${this.t['Items']}`,
})[err.type];
if (err.type=="string.regex.name") {
if (err.context.name=="alphabeta") err.message = `${this.t['Letters only']}`;
if (err.context.name=="alphanum") err.message = `${this.t['Letters and digits only']}`;
if (err.context.name=="num") err.message = `${this.t['Digits only']}`;
if (err.context.name=="latin") err.message = `${this.t['Entered invalid chars']}`;
if (err.context.name=="username") err.message = `${this.t['Letters and digits only in english']}`;
}
return err;
});
}
}
And this is how I set it:
let jce = new JoiCustomErrors($rootScope.t);
let schema = Joi.object().keys({
first_name: Joi.string().min(2).max(5).required().error(jce.parser)
});
Joi.validate({first_name: "a"}, schema, { abortEarly: false }, err => {
console.log(err);
return err;
});
The above code sends errors to the parser method in the JoiCustomErrors class.
However the $rootScope.t which was declared in the instance declaration is not accessible.
How to fix this?