2011-09-20 174 views
2

我有我的工作與下面的簡單情況:Knockout.js fromJSON不更新視圖模型

從ASP.NET MVC控制器,它看起來像
<ul data-bind='template: {name : "namesTemplate", data:viewModel}'> 
</ul> 

<script id='namesTemplate' type='text/html'> 
    {{each $data}} 
     <li>${ Name }</li> 
    {{/each}} 
</script> 

<span data-bind="click: fire">Click Me</span> 

<script type='text/javascript'> 

    var viewModel = ko.observableArray([{ "Name": "Tom" }, 
             { "Name": "Pete" }, 
             { "Name": "Dave"}]); 

    viewModel.fire = function() { 
     $.getJSON("Post", function (result) { 
      viewModel = ko.mapping.fromJSON(result); 
     }); 
    } 

    ko.applyBindings(viewModel); 

</script> 

getJSON越來越JSON數據

[{"Name":"Chris"}] 

一旦點擊Click Me無序列表沒有被更新。我哪裏錯了?

謝謝。

回答

0

看一看我的例子:

http://jsfiddle.net/YhXyL/

var viewModel ={ 
     names: ko.observableArray([{ "Name": "Tom" }, 
           { "Name": "Pete" }, 
           { "Name": "Dave"}]) 
}; 

viewModel.fire = function() { 
    this.names([{"Name": "test"}]); 
}; 

ko.applyBindings(viewModel); 

和HTML:

<ul data-bind='template: {name : "namesTemplate", foreach:names}'></ul> 

<span data-bind="click: fire">Click Me</span> 

<script id='namesTemplate' type='text/html'> 
    <li data-bind="text: Name"/> 
</script> 

如果你想添加新的陣列可以使用按鍵方法:

this.names.push([{"Name": "test"}]); 
+0

嘿,歡呼的迴應。當嘗試這個時,我收到錯誤:Uncaught TypeError:Object function(d,b){var a = b?d.bind(b):d,f = new p。$ a(a,function(){paN(e ,f)}); e.push(f); return f}沒有方法'each' - 任何想法? – youwhut

2

個兩個想法:

1)在您的視圖模型命名屬性:

var viewModel = { employees: ko.observableArray([{ "Name": "Tom" }, 
               { "Name": "Pete" }, 
               { "Name": "Dave"}]); 
}; 

2)當你已經在你的視圖模型的數據,也許你應該使用ko.mapping.updateFromJS

viewModel.fire = function() { 
    $.getJSON("Post", function (result) { 
     ko.mapping.updateFromJS(viewModel.employees, result); 
    }); 
} 
相關問題