Meteor - 箭头函数打破 ES6 中的#each 循环

Meteor - Arrow Functions breaking #each loop in ES6

我希望我有合适的区域来要求这个... 下面是我正在处理的两个文件中的一些代码。当我将函数中带有“this.”的任何内容更改为箭头函数时,代码不再按预期运行。

有人能解释我做错了什么吗?使用箭头函数时是否需要做一些不同的事情?我一开始就错误地使用了 'this.' 吗?我不应该以这种方式使用箭头函数吗?

非常感谢帮助。

client/views/jobList.html

{{#each jobs}}
    <tr>
        <td>{{jobID}}</td>
            <td>{{user.fullname}}</td>
            <td>{{product.type}}</td>
            <td>{{shortDesc}}</td>
            <td>{{formattedDate}}</td>
            <td>{{phone}}</td>
            <td>{{user.username}}</td>
            <td>{{jobType}}</td>
            <td>{{product.brand}}</td>
            <td>{{product.type}}</td>
            <td>{{product.model}}</td>
        </tr>
    {{/each}}

client/views/jobList.js

Template.jobList.helpers({
    jobs: ()=> Jobs.find({}, {sort: {jobDate: 1}}),

    formattedDate: function() { // Changing this to arrow function breaks functionality
        let d = this.jobDate;
        let e = formatDate(d);
        return e;
    },
    shortDesc: function () { // Changing this to arrow function breaks functionality
        if (this.description.length > 40) {
            return this.description.substr(0, 50) + '...';
        } else {
            return this.description
        }
    },
    jobID: function () { // Changing this to arrow function breaks functionality
        let a = this.jobNum;
        let e = this.jobType.substr(0, 1);
        return e + a
    }
});

箭头函数的基本特征之一是它们在创建它们的上下文中继承(关闭this。您的代码依赖于通过调用函数的方式设置的 this,因此箭头函数不是一个好的选择。

下面是差异和问题的说明:

var obj = {
    foo: () => {
        console.log("foo: this.prop:", this.prop);
    },
    bar: function() {
        console.log("bar: this.prop:", this.prop);
    },
    prop: "the property"
};
obj.foo(); // Doesn't show `prop` because `this` != `obj`
obj.bar(); // Does show `prop` because `this` == `obj`