gpt4 book ai didi

javascript - Aurelia:如何在激活期间在 View 模型上设置属性?

转载 作者:行者123 更新时间:2023-11-30 15:41:07 25 4
gpt4 key购买 nike

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

我在尝试在 Aurelia View 模型中设置属性时遇到 javascript 范围问题。在下面的代码中,当我的 API 调用完成并且我在激活方法中输入 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;
});
}
}

最佳答案

原来我的问题来自 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;
});
}
}

关于javascript - Aurelia:如何在激活期间在 View 模型上设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com