需要将用户定义的关键字函数绑定到一个对象上。具体方法是使用箭头函数而不是普通函数,并且使用bind()方法将上下文绑定到对象。 示例如下:
const ajv = new Ajv();
ajv.addKeyword('myKeyword', {
validate: function(data, dataPath, parentData, parentDataPath, rootData) {
return true;
},
// 修改前:
// validate: function validate(schema, data) {
// const context = this.keywordContext;
// const schemaData = context.schema;
// return data === schemaData;
// },
$data: true,
metaSchema: {
type: 'boolean'
},
// 修改后:
validate: ((schema, data) => {
const context = this.keywordContext;
const schemaData = context.schema;
return data === schemaData;
}).bind(this),
errors: 'full',
modify: true,
passContext: true
});
const schema = {
type: 'object',
properties: {
myProp: {
type: 'string',
myKeyword: true // 使用关键字
}
}
};
const validate = ajv.compile(schema);
console.log(validate({ myProp: 'hello' })); // true
在上面的示例中,我们通过将validate函数转换为箭头函数并将其绑定到当前对象(使用.bind(this)方法)来修复了“AJV: can't get any context with { passContext: true } since "this" is undefined in user-defined keyword function”的问题。