Aurelia 在函数中访问和更新 public 属性 的值

Aurelia accessing and updating values of a public property in function

从函数访问 public 属性 的最佳方法是什么?

我有一个场景,当一个函数被执行时,它应该更新一个 public 属性 这是一个对象/数组。

下面是我的代码:

TS文件

formName = "support";
  formTemplate = {
    "types": [
      "text",
      "file",
      "number",
      "email"
    ],
    "support": {
      "description": "This will generate form for support request",
      "fields": [
        {
          "name": "title",
          "element": "input",
          "type": "text",
          "label": "Title",
          "placeHolder": "Provide Short Discription",
          "classes": "form-control",
          "value": ""
        },
        {
          "name": "description",
          "element": "input",
          "type": "text",
          "label": "Description",
          "placeHolder": "Provide Discription",
          "classes": "form-control",
          "value": ""
        },
        {
          "name": "email",
          "element": "input",
          "type": "text",
          "label": "Email",
          "placeHolder": "Provide email addresses",
          "classes": "form-control",
          "value": ""
        },
        {
          "name": "attachment",
          "element": "file-picker",
          "type": "file",
          "label": "Attachment",
          "placeHolder": "Insert Attachment",
          "classes": "form-control",
          "value": "test"
        }
      ]
    }
  };  

  public processForm(data) {
    this.formTemplate.support.fields.forEach(function (item, i) {
      if (item.element === 'file-picker') {
        // THIS DOESN'T WORK. NEED TO ACCESS formTemplate and update value for a property
        console.log(this.formTemplate.support.fields[i].value);
      }
    });
  }

因此,当 processForm 在单击时从视图执行时,它应该能够访问 formTemplate 对象。由于 this 在函数中是局部的,因此在访问函数范围之外的 formTemplate 时需要帮助。

非常感谢任何帮助。 :)

将您的 function() 更改为 arrow functions =>,因为它们保留了它们声明的范围,因此 this 指的是 class 而不是函数。

public processForm(data) {
    this.formTemplate.support.fields.forEach((item, i) => {
      if (item.element === 'file-picker') {
        console.log(this.formTemplate.support.fields[i].value);
      }
    });
  }