2015-06-04 36 views
1

我有這樣的視圖模型:`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屬性未定義。

我該如何解決這個問題?

回答

2

由於要傳遞的功能,別人在.then(this.activateView);叫你需要自己保持的背景下,最好的,如果你這樣做:.then((view)=>this.activateView(view));

更多thishttps://www.youtube.com/watch?v=tvocUcbCupA

+1

是的,這個被稱爲詞法範圍,更多信息可以在這裏找到:http://www.typescriptlang.org/Handbook#functions-lambdas-and-using-39this39 – Brocco

1

你也可以做再( this.activateView.bind(本))

2

雖然你有你的答案,我喜歡的方式是有點不同:

轉換函數/方法定義 - 爲 「財產引用函數」

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

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

這將減少需要通過這樣的

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

明確PARAMS,因爲這將重新工作:

.then(this.activateView)