简体   繁体   English

Angular2在回调中访问绑定实例变量

[英]Angular2 accessing binding instance variable within callback

In angular2 I have the following component: 在angular2中,我具有以下组件:

import { Component } from '@angular/core';

const dialog = require("electron").dialog;
const xml2js = require('xml2js');
const fs = require("fs");
const ipc = require('electron').ipcRenderer;

@Component({
  selector: 'ct-config-editor',
  templateUrl: 'config.editor.component.html'
})
export class ConfigEditorComponent {

  constructor() {
    this.selected_file = 'Max';
  }


  clicked(event){
    alert("lol");
      ipc.send('open-file-dialog');

      ipc.on('selected-directory', function (event, path) {
        this.selected_file = `You selected: ${path}`;
      });
  }
}

The view has a correctly bound property called selected_file like this : 该视图具有正确绑定的属性,称为selected_file,如下所示:

<h1>{{selected_file}}</h1>

The value of the H1 is max at the start -- however after my callback runs, I don't have access to the this.selected_file because the context of the 'this' is not my class. H1的值在开始时是最大值-但是,在我的回调运行之后,我无法访问this.selected_file因为“ this”的上下文不是我的课程。

How do I access my instance variable within the callback? 如何在回调中访问我的实例变量?

Use arrow function to retain context: 使用箭头功能保留上下文:

ipc.on('selected-directory', (event, path) => {
   this.selected_file = `You selected: ${path}`;
});

This way this will be referenced to your class 这样, this将被引用给您的班级

See also more details here 在这里查看更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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