How to convert an array to Collection in backbone

一个人想着一个人 提交于 2019-12-06 07:10:09

A Backbone collection expects a list of models/hashes of attributes that can be converted to a model but you have a plain array.

You will have to transform your array to a list of hashes. Assuming your values are the ids of your models :

var lst = _.map(this.noOfHouseHold, function(val) {
    return {id: val};
});
var adultListCollection = new Backbone.Collection(lst);

Backbone.Collection expects a list of models or objects (because they can be converted to Backbone.Model). In order to persist the array you have to convert those primitives into objects. Use Backbone.Collection.parse and _.map to turn your array of primitives into an array of objects:

var AdultListCollection = Backbone.Collection.extend({
  parse: function (noOfHouseHold) {
    var res = _.map(noOfHouseHold, function (n) {
        return {id: n};
    });
    return res;
  }
});

Now you can instantiate your Collection with an array:

var adultListCollection = new AdultListCollection(this.noOfHouseHold, {parse: true});

Example: JSFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!