回调中的`this`指向错误的对象

时间:2015-06-04 02:22:47

标签: typescript

我有这个viewModel:

import app = require("durandal/app");
import appViewModel = require("appViewModel");
import dataService = require("dataService");

class Home{
    section = ko.observable<string>();
    activeScreen = ko.observable<string>("nativeLanguage/selectNativeLanguage");

constructor() {
    app.on('home:activateView').then(this.activateView);
}

activateView(view) {
    this.activeScreen(view);
}

activate() {
    return this.getSection();
}

getSection() {
    return dataService.getSection('HOME_PAGE').then((data) => {
        this.section(data.results[0]);
    });
}
}
export = Home;

编译没有错误。

但是,当它运行时,并且activateView被称为回调,this指向app而不是Home,因此未定义activeScreen属性。

如何解决此问题?

3 个答案:

答案 0 :(得分:2)

由于您正在将该功能传递给其他人以便在.then(this.activateView);中进行呼叫,因此您需要自己保留上下文,最好是:.then((view)=>this.activateView(view));

有关this的更多信息:https://www.youtube.com/watch?v=tvocUcbCupA

答案 1 :(得分:2)

虽然你有答案,但我喜欢的方式有点不同:

  

函数/方法定义转换为&#34; 属性引用函数&#34;

// instead of class method
// public activateView(view) {

// use the "property"
public activateView = (view) => {
    this.activeScreen(view);
}

这将减少传递这样的显式参数的需要

.then((view) => this.activateView(view))

因为这会再次起作用:

.then(this.activateView)

答案 2 :(得分:1)

你也可以这样做(this.activateView.bind(this))