2

new to Backbone and underscore js here.

I have an array of arrays that I want to convert to a collection of models.

So it's like

{ {1, 2, 3, 4}, {5, 6, 7, 8}}

The second level of arrays is what's going into a backbone model. Right now, I have

collection.reset(_.map(results, (indvidualResults) -> new model(individualResults))

Which doesn't work as when I do a console.log(collection.pop) I get a function printed out. I think this is because I'm working with an array of arrays (but I could be wrong). How do I convert the second array into a model and then put that into a collection?

2
  • (1) What does your data really look like? (2) Why are you doing the _.map when Collection#reset will do all that for you? (3) Collections have a pop method so of course console.log(collection.pop) gives you a function. Commented Jul 13, 2012 at 22:44
  • Do you mean console.log(collection.pop())? console.log(collection.pop)*should* give you a function. Commented Jul 14, 2012 at 23:20

1 Answer 1

9

Reshape your raw data to look more like:

[{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}]

Assuming you have a model and collection defined something like:

var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
    model: Model
});

Then just pass the array of attribute hashes into the reset method:

var results = [{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}];
var collection = new Collection();
collection.reset(results);
var model = collection.pop();
console.log(JSON.stringify(model.toJSON());
Sign up to request clarification or add additional context in comments.

1 Comment

collection.reset(results); works fine. But looks like it doesn't execute .parse() method on each model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.