ceth
ceth

Reputation: 45295

Pass class method as parameter to underscore.js

Here is my code:

export class DefectResource {

   setFormattedDateForDefect(defect) {
        defect.startFormatted = this.dateConverter.convertFromUnixDate(defect.start);
        defect.finishFormatted = this.dateConverter.convertFromUnixDate(defect.finish);
        return defect;
    };

    setFormattedDateForDefects(defects) {
        return _.map(angular.fromJson(defects), this.setFormattedDateForDefect);
    };
}

I am calling setFormatedDateForDefects() for collection of objects and this method must call setFormattedDateForDefect() for each method of this collection. But don't call.

I know that the reason is this keyword which in this context is not an Object, but I don't know how to fix it.

How can I fix the code?

Upvotes: 0

Views: 67

Answers (1)

Daniel Cook
Daniel Cook

Reputation: 244

You can use the => syntax for method declarations which will ensure they are always bound to the "correct" this.

export class DefectResource {
    setFormattedDateForDefect = (defect) => {
        defect.startFormatted = this.dateConverter.convertFromUnixDate(defect.start);
        defect.finishFormatted = this.dateConverter.convertFromUnixDate(defect.finish);
        return defect;
    };

    setFormattedDateForDefects = (defects) => {
        return _.map(angular.fromJson(defects), this.setFormattedDateForDefect);
    };
}

Upvotes: 1

Related Questions