Chuck Conway
Chuck Conway

Reputation: 16435

How to ignore a block of code when transpiling with BabelJs?

I'm trying to reference this in ES2015, with Babeljs. This problem I am having is Babeljs keeps moving this out of the scope into the external scope. This breaks the code. I am hoping Babeljs has a comment, or some sort of block notation I can use to have it ignore the code so it won't be transpiled.

If there are any Mongoose guru's out there, maybe there is another way to access the property and function in question (this.isNew || this.isModified('email')).

Here is the ES2015 code.

setDuplicateEmailValidation(){
    this.schema.path('email').validate((email, fn) => {
        let User = mongoose.model('User');

        // Check only when it is a new user or when email field is modified
        if (this.isNew || this.isModified('email')) {
            User.find({ email: email }).exec((err, users) => {
                fn(!err && users.length === 0);
            });
        } else fn(true);
    }, 'Email already exists');
}

In the if-statement if (this.isNew || this.isModified('email')) the pre-transpiled code has references to this. The scope of validate() is important because while in this scope I have access to Mongoosejs's Document API. Once the code moves out of the validate() scope I no longer have access to the Document API.

Transpiled code.

function setDuplicateEmailValidation() {
            var _this = this;
        this.schema.path('email').validate(function (email, fn) {
            var User = _mongoose2['default'].model('User');

            // Check only when it is a new user or when email field is modified
            if (_this.isNew || _this.isModified('email')) {
                User.find({ email: email }).exec(function (err, users) {
                    fn(!err && users.length === 0);
                });
            } else fn(true);
        }, 'Email already exists');
    }
}

In this code, you'll notice that the if-statement references a variable (if (_this.isNew || _this.isModified('email'))) that is outside the scope of the validate function. Because of this (no pun intended) move, I am losing access to Mongoosejs's Document API.

Any suggestions will be greatly appreciated.

Upvotes: 1

Views: 837

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

Don't use arrow function, just use the function keyword:

this.schema.path('email').validate(function (email, fn) {

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.

Emphasis mine. This means that thisinside the arrow function will be this in the same lexical context outside the arrow function. This is intentional and different from function syntax.

Upvotes: 4

Related Questions