在Knockout中映射数组

时间:2014-01-05 04:31:19

标签: json knockout.js knockout-mapping-plugin

这是我从我的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: competition@bernese.org.nz. 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:'...'}]}

感谢。

编辑: 我的错误,我已将items定义为observableArray。我这样使用它,所以只要页面加载,就会显示加载器gif。我之前已经这样做了,这次唯一的区别就是json的格式返回了。

ADDED:这是example

2 个答案:

答案 0 :(得分: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);
})

更新:Here is a fully working jsfiddle

答案 1 :(得分: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