Aurelia在功能中访问和更新公共财产的值

时间:2018-04-13 14:37:51

标签: typescript aurelia

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

我有一个场景,当一个函数执行时,它应该更新一个对象/数组的公共属性。

以下是我的代码:

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

非常感谢任何帮助。 :)

1 个答案:

答案 0 :(得分:1)

将您的function()更改为enter image description here =>,因为它们会保留声明它们的范围,因此this指的是类而不是函数。

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