admin管理员组文章数量:1336737
I have an array defined as:
this.noOfHouseHold = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
I'm trying to convert it to a Backbone Collection as:
var adultListCollection = new Backbone.Collection(this.noOfHouseHold);
It gives me the list but for 2 digit numbers, it shows something like this:
attributes: Object
0: "1"
1: "1"
I'm not able to understand as to what is wrong here or is it the wrong way I'm converting my array to collections. Please suggest. Thanks in advance!
I have an array defined as:
this.noOfHouseHold = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
I'm trying to convert it to a Backbone Collection as:
var adultListCollection = new Backbone.Collection(this.noOfHouseHold);
It gives me the list but for 2 digit numbers, it shows something like this:
attributes: Object
0: "1"
1: "1"
I'm not able to understand as to what is wrong here or is it the wrong way I'm converting my array to collections. Please suggest. Thanks in advance!
Share Improve this question asked Jul 22, 2015 at 7:47 Abhishek Singh ThakurAbhishek Singh Thakur 331 silver badge3 bronze badges2 Answers
Reset to default 4A 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 id
s 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
本文标签: javascriptHow to convert an array to Collection in backboneStack Overflow
版权声明:本文标题:javascript - How to convert an array to Collection in backbone - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742385854a2465018.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论