2013-02-03 180 views
0

我花了一些時間試圖找出爲什麼綁定不成功的HTML部分中'(不工作綁定)'沒有成功。 我有一個簡單的玩家列表;當點擊其中一個時,我應該看到底部頁面中綁定的名稱發生變化: 1)與vm.selectedPlayerName綁定的玩家名稱正確顯示 2)與vm.selectedPlayer.name()綁定的玩家名稱顯示正確僅在頁面加載時和從不點擊事件時,即使控制檯日誌在selectedPlayer對象中顯示適當的更改。 我想使2)的工作,以避免重新定義視圖模型中的屬性。 我在做什麼錯?淘汰賽綁定對象

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script> 
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js'></script> 
<script> 
    $(document).ready(function() { 
     var my = {}; //my namespace 
    // Player 
    my.Player = function() { 
     this.name = ko.observable(""); 
    }; 

    // The ViewModel 
    my.vm = function() { 
     var 
     players = ko.observableArray([]), 
     selectedPlayer = ko.observable(), 
     selectedPlayerName = ko.observable(""), 

     goToDetails = function (aPlayer) { 
      my.vm.selectedPlayer = aPlayer; 
      my.vm.selectedPlayerName(my.vm.selectedPlayer.name()); 
      console.log("goToDetails: ", my.vm.selectedPlayerName()); 
     }, 

     loadPlayers = function() { 
      my.vm.players.push(new my.Player().name("Player1")); 
      my.vm.players.push(new my.Player().name("Player2")); 
      my.vm.players.push(new my.Player().name("Player3")); 
      my.vm.selectedPlayer = my.vm.players()[0]; 
      my.vm.selectedPlayerName(my.vm.selectedPlayer.name()); 
     }; 

     return { 
      // Data 
      players: players, 
      selectedPlayer: selectedPlayer, 
      selectedPlayerName: selectedPlayerName, 
      // Other 
      loadPlayers: loadPlayers, 
      goToDetails: goToDetails, 
     }; 
    }(); 

    my.vm.loadPlayers(); 
    ko.applyBindings(my.vm); 
    }); 
</script> 
<title></title> 
</head> 
<body> 
<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: players"> 
     <tr> 
      <td data-bind="text: name, click: $root.goToDetails"></td> 
     </tr> 
    </tbody> 
</table> 
<p> 
    Selected player (working binding on click): <span data-bind='text: $root.selectedPlayerName'></span> 
    <br /> 
    Selected player (not working binding on click): <span data-bind='text: selectedPlayer.name()'></span> 
</p> 

</body> 

回答

2

的問題是,你並沒有使用一些東西到SelectedPlayer觀察到:

goToDetails = function (aPlayer) { 
     my.vm.selectedPlayer = aPlayer; 
     ... 
    }, 

應該是:

goToDetails = function (aPlayer) { 
     my.vm.selectedPlayer(aPlayer); 
     .... 
    }, 

記住,可觀察到的在技術上是一個功能。當您通過賦值運算符賦值時,您將其作爲函數覆蓋它,將其替換爲僅在淘汰模型中的頁面加載時處理的對象。