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

标签 javascript meteor ecmascript-6 meteor-blaze

我希望我有正确的区域来要求这个...... 下面是我正在处理的两个文件中的一些代码。当我用 ' 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`

关于javascript - Meteor - 箭头函数打破 ES6 中的 #each 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37784717/

相关文章:

JavaScript:为什么我的 HTML 中会出现 "quotes"?

javascript - 在 react 中丢失页面刷新时的组件数据

javascript - 如何读取已设置的超时句柄还剩多少时间?

javascript - meteor .js : time-based server calls?

javascript - 如何使用 Meteor 在 Mongo 中插入 N 个元素到文档中

javascript - ES6 类,传递函数作为参数来注册 expressjs 路由

javascript - 删除文件时停止 fs.createWriteStream 创建可写流

meteor - 我可以撤销更新 Meteor 吗?

具有日期升序的Javascript数组过滤器并删除重复项

javascript - 使用 Javascript/es6 生成二维数组