简体   繁体   中英

Aurelia accessing and updating values of a public property in function

What is the best approach to access public property from a function?

I have a scenario where when a function is executed, it should update a public property which is an object / array.

Below is my code:

TS file

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);
      }
    });
  }

So when processForm is executed from view on click, it should be able to access formTemplate object. Since this is local with in the function, need help on accessing formTemplate which is outside function scope.

Any help is really appreciated. :)

Change your function() to arrow functions => , as they preserve the scope in which they're declared, and therefore this refers to the class instead of the function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM