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

时间:2016-11-25 03:15:45

标签: javascript ecmascript-6 aurelia aurelia-binding

免责声明:我对Aurelia非常陌生,所以这可能是一个显而易见的问题。

尝试在Aurelia视图模型中设置属性时,我遇到了javascript范围问题。在下面的代码中,当我的API调用完成并且我在activate方法中输入promise时,“this”是未定义的。关于我在这里做错了什么想法?

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

1 个答案:

答案 0 :(得分:2)

原来我的问题来自于ES2015箭头功能解决的范围问题。通过使用典型的匿名函数声明,“this”的范围已更改。用箭头函数替换匿名函数可以正确处理范围:

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