2014-01-05 107 views
1

数组这里是我已经嘲笑了我的MVC代码:映射在淘汰赛

$(function(){ 

    var ViewModel = function(){ 
     this.items = ko.observableArray(null); 
     this.isLoading = ko.observable(true); 
    }; 

    var data = [{"CreatedAt":"2013-12-29T22:00:20","Intro":"","Body":"","Title":"Test Item","Url":"/news-items/test-item/"},{"CreatedAt":"2013-12-29T21:13:34","Intro":"","Body":"","Title":"Test 1","Url":"/news-items/test-1/"},{"CreatedAt":"2013-12-29T16:03:56","Intro":"","Body":"<p>In the spirit of Christmas we are holding a Christmas photo competition for all members to enter. Prizes will be given to the best Christmas themed photo and the funniest photo.&nbsp; To enter, simply email your photo to: [email protected] Your entry will be uploaded onto the club's Facebook page where all members can then vote by 'liking' their favourite photo.</p>\n<p>Entries close on the 20th of December and voting will be open until the 5th of January. The winning photo's will be displayed on the website.</p>","Title":"Christmas 2013 Photo Competition","Url":"/news-items/christmas-2013-photo-competition/"}]; 
    var vm = new ViewModel(); 
    ko.applyBindings(vm); 
    vm.items(test); 
    vm.isLoading(false); 
}) 

我从我的MVC编码嘲笑它,但data对象基本上就是从我的控制器返回。 Knockout映射在这种情况下不起作用,我怀疑这是我的数据返回的方式。这是一种有效的方式,还是我需要将其包装在各种DTO中,例如:{ items: [{item1:'...'},{item2:'...'}]}

谢谢。

编辑: 我的错误,我已经定义为itemsobservableArray。我以这种方式使用它,只要页面加载显示的加载程序gif。我之前就是这样做的,这次唯一的区别就是返回的json的格式。

新增:这里的example

回答

0

ko.mapping.fromJS(data)返回一个ko.observableArray如果data参数已经是一个数组。

所以你需要指定它之前解开返回ko.observableArray

var vm = new ViewModel(); 
ko.applyBindings(vm); 
var test = ko.mapping.fromJS(data); 
vm.items(test()); // you need to write `test()` to get the underlaying array. 

或者你也可以直接填写您已经声明ko.observableArray写作:

var vm = new ViewModel(); 
ko.applyBindings(vm); 
ko.mapping.fromJS(data, {} /* mapping options */, vm.items); 

这里是你的更新JSFiddle

1

我不知道这是不是唯一的问题,但

this.items = ko.observable(null); 

应该

this.items = ko.observableArray(); 

但我可能做整个事情更像

$(function(){ 
    var ViewModel = function(items){ 
     this.items = ko.observableArray(items); 
    }; 

    var data = [...]; 
    var vm = new ViewModel(data); 
}) 

UPDATE:Here is a fully working jsfiddle

+0

谢谢,我也试过这个,它也不工作。看起来'ko.mapping.fromJS(data)'的输出是正确的,所以我必须在这里丢失一些基本的东西。这是我最近的例子:http://jsfiddle.net/u54mn/10/ – codedog

+0

我更新了我的答案与工作jsfiddle。主要的问题是两次映射observableArray - 你不需要,因为fromJS会为你返回一个可观察数组。 –