简体   繁体   English

Aurelia:如何在激活期间在视图模型上设置属性?

[英]Aurelia: How to set property on view model during activate?

Disclaimer: I'm VERY new to Aurelia so this might be an obvious question. 免责声明:我对Aurelia非常陌生,所以这可能是一个显而易见的问题。

I'm having a javascript scope issue while trying to set a property in an Aurelia view model. 尝试在Aurelia视图模型中设置属性时遇到javascript范围问题。 In the following code, when my API call completes and I enter the promise in the activate method 'this' is undefined. 在下面的代码中,当我的API调用完成并且我在activate方法中输入promise时,“ this”是未定义的。 Any ideas on what I'm doing wrong here? 对我在这里做错的任何想法吗?

import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";

@inject(HttpClient)
export class ListTasks{

    constructor(httpClient) {
        this.http = httpClient; 
        this.tasks = [];
    }

    activate() {
        this.http.get('api/task').then(function(result){
            // 'this' is undefined in the scope of this function
            this.tasks = result.content;
        });
    }
}

Turns out my issue was coming from a scoping issue that ES2015 arrow functions solve. 原来我的问题来自ES2015箭头功能解决的范围问题。 By using an typical anonymous function declaration, the scope of 'this' was changed. 通过使用典型的匿名函数声明,更改了“ this”的范围。 Replacing the anonymous function with an arrow function handles the scope properly: 用箭头函数替换匿名函数可以正确处理范围:

 import {inject} from "aurelia-framework"; import {HttpClient} from "aurelia-http-client"; @inject(HttpClient) export class ListTasks{ constructor(httpClient) { this.http = httpClient; this.tasks = []; } activate() { this.http.get('api/task').then(result => { // 'this' is undefined in the scope of this function this.tasks = result.content; }); } } 

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

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