为什么我的knockout observable没有被更新?

Why isn't my knockout observable being updated?

本文关键字:更新 我的 knockout observable 为什么      更新时间:2023-09-26

我的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);
编辑:

我是这样解决这个问题的:

var dashboardViewModel = {
  currentPlayer: ko.observable({"player_id": ""}),
  vsPlayer: ko.observable("VS: ALL PLAYERS")
};
ko.applyBindings(dashboardViewModel);
$.get("/players/summary", dashboardViewModel.currentPlayer);

要设置一个可观察对象的值,你需要将新值作为第一个参数传入(与初始化时相同)。

那么,在你的回调中,你会想要这样做:dashboardViewModel.currentPlayer (json.player_id);

修改原始对象不会更新currentPlayer的值