【问题标题】:Angular2 accessing binding instance variable within callbackAngular2在回调中访问绑定实例变量
【发布时间】:2017-03-10 15:15:32
【问题描述】:

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

视图有一个正确绑定的属性,称为 selected_file,如下所示:

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

H1 ​​的值在开始时是最大值 -- 但是在我的回调运行后,我无法访问 this.selected_file,因为“this”的上下文不是我的类。

如何在回调中访问我的实例变量?

【问题讨论】:

    标签: javascript angular electron


    【解决方案1】:

    使用箭头函数保留上下文:

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

    这样this 将被您的班级引用

    在此处查看更多详细信息

    【讨论】:

    • 这是最佳实践吗?不是特别明白箭头函数是干什么的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    相关资源
    最近更新 更多