Jeremy Smith
Jeremy Smith

Reputation: 15079

Why isn't my knockout observable being updated?

My html is showing "placeholder" upon initialization of the page, but then is not getting updated by my ajax call. Is there some kind of scoping issue?

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:

This is how I solved the issue:

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

ko.applyBindings(dashboardViewModel);

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

Upvotes: 2

Views: 1353

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

To set an observable's value, you need to pass the new value in as the first argument (same ad when you initialized it).

So, in your callback, you would want to something like: dashboardViewModel.currentPlayer(json.player_id);

Modifying your original object would not update currentPlayer's value.

Upvotes: 3

Related Questions