我有這樣的視圖模型:`this`回調點錯了對象
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屬性未定義。
我該如何解決這個問題?
是的,這個被稱爲詞法範圍,更多信息可以在這裏找到:http://www.typescriptlang.org/Handbook#functions-lambdas-and-using-39this39 – Brocco