2011-12-17 18 views
2

私のHTMLは、ページの初期化時に "プレースホルダ"を表示していますが、私のajax呼び出しでは更新されません。スコープの問題がありますか?私のノックアウト観測可能性が更新されないのはなぜですか?

var currentPlayer = { 
    "player_id": "placeholder" 
}; 

$.ajax({ 
    url: "/players/summary", 
    success: function(json) { 
    // when this ajax call is completed the placeholder string is not replaced by 
    // currentPlayer.player_id. I have verified that the currentPlayer hash does 
    // have that value after this ajax call 
    currentPlayer = json; 
    } 
}); 

var dashboardViewModel = { 
    // <span data-bind="text:currentPlayer"></span> displays the "placeholder" 
    // string upon initialization 
    currentPlayer: ko.observable(currentPlayer.player_id), 
    vsPlayer: ko.observable("VS: ALL PLAYERS") 
}; 

ko.applyBindings(dashboardViewModel); 

EDIT:

これは私が問題を解決する方法である:

var dashboardViewModel = { 
    currentPlayer: ko.observable({"player_id": ""}), 
    vsPlayer: ko.observable("VS: ALL PLAYERS") 
}; 

ko.applyBindings(dashboardViewModel); 

$.get("/players/summary", dashboardViewModel.currentPlayer); 

答えて

3

、観察の値を設定するには、あなたが最初の引数(同じ広告ときのように新しい値を渡す必要がありますあなたはそれを初期化しました)。

あなたのコールバックでは、次のようになります。 dashboardViewModel.currentPlayer(json.player_id);

元のオブジェクトを変更しても、currentPlayerの値は更新されません。

+1

バインディングのポイントは、元のデータ構造を変更してUIに伝播させるだけではありませんか?ダッシュボードViewModelハッシュ/クラス内でその接続を作成する方法はありますか? –

+0

変更に反応する必要があるものはすべて、オブザーバブルを通過する必要があります。通常のパターンは元のデータを取得し、それを観測可能な構造体に変換し、それをサーバに渡す前に 'ko.toJS'または' ko.toJSON'を使って元に戻すことです。 –

関連する問題