2014-01-24 27 views
1

我是新來使用Knockoutjs,我一直有一個問題,我難住。我從服務器獲得一個json對象,這是一個對象集合,我試圖使用knockoutjs將它綁定到一個列表。有一些我雖然失蹤。我不確定如何引用正在綁定的視圖模型中的當前對象。databinding JSON收集與knockoutjs

function GetGameListResponse(response) 
{ 
    if (response.Error == null) 
    { 
     // this is my test, when I bind the collection directly everything works fine... 
     //ko.applyBindings(response, document.getElementById('panGames')); 

     // this doesn't work 
     ko.applyBindings(new ListViewModel(response), document.getElementById('panGames')); 
    } 
} 
function ListViewModel(response) 
{ 
    var self   = this; 

    // this is where the problem is I think, as 'response' 
    self.Id    = ko.observable(response.Id); 
    self.Name   = ko.observable(response.Name); 
    self.Date   = ko.observable(response.Date); 
    self.Description = ko.observable(response.Description); 

} 

...這裏是將其綁定到HTML:

<table> 
<thead> 
<tr> 
    <th>Name</th> 
    <th>Date</th> 
    <th>Description</th> 
    <th>select</th> 
</tr> 
</thead> 
<tbody data-bind="foreach: List"> 
<tr> 
    <td data-bind="text: Name"></td> 
    <td data-bind="text: Date"></td> 
    <td data-bind="text: Description"></td> 
    <td></td> 
</tr> 
</tbody> 
</table> 

的JSON是編號,姓名,日期等對象的可預見的集合,如果我不工作正常嘗試使用視圖模型將集合綁定到UI。我一定是簡單的東西在這裏...

+0

您可以發佈樣本JSON ? – nemesv

+1

{列表:[{名稱:「FirstThing」,日期:「1/22/13」,說明:「Fooo」},{名稱:「SecondThing」,日期:「1/23/13」,說明:「Fooo 「}]} – MadTigger

回答

1

那麼假設response是這樣的:

{ 
    List: [ 
     { 
      Name: "Name", 
      Date: "Date", 
      Description: "Description" 
     } 
    ] 
} 

您的視圖模型將是這個樣子:

function ListViewModel(response) 
{ 
    var self   = this; 

    var list = []; 
    for (var i = 0; i < response.List.length; i++) { 
     list.push(new ListItemViewModel(response.List[i])); 
    } 
    self.List = ko.observableArray(list); 
} 

function ListItemViewModel(data) 
{ 
    var self   = this; 

    self.Id    = ko.observable(data.Id); 
    self.Name   = ko.observable(data.Name); 
    self.Date   = ko.observable(data.Date); 
    self.Description = ko.observable(data.Description); 
} 
+0

有趣。我不知道爲什麼使用自變量,但它會在兩個JavaScript函數中都需要嗎?我注意到你的示例中有一個錯誤,應該是:list.push(new ListItemViewModel(response.List [i]));這是否意味着我需要將數據綁定語法更改爲引用ListItemViewModel對象的內容,因爲沒有包含列表的列表了? – MadTigger

+0

不,在這些視圖模型中,您可以使用'this'而不是'self'。 'self'被定義爲當你在視圖模型中的函數中時,你仍然可以訪問視圖模型(因爲'this'根據上下文指向不同的對象)。 – sroes

+0

你說得對,我的代碼不正確;我更新了我的答案。數據綁定語法應該是正確的,因爲您正在循環「List」。這意味着你可以在'foreach'中使用'ListItemViewModel'的所有屬性。 – sroes