Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting each model from a Backbone Collection

I'm convinced this is a very easy fix, but none of the posts I've found so far seem to have addressed this directly: how do I loop over a collection to get each model?

The first method I'm trying to use is underscore's each method. Here is my call and function:

collection_var.each(paintThings);

and here is my function:

function paintThings() {
        console.log(this);
        console.log(this.model);
            var thing_type = this.model.get("type"),
                thing_other = this.model.get("otherAttribute");

                console.log(this.model);
                console.log(thing_type);
                console.log(thing_other);
        }

Right now, this comes out as undefined, and this.model errors:

Uncaught TypeError: Cannot read property 'model' of undefined 

I know the answer is simple, but it's driving me crazy! I'm new to underscore. Can anyone here help? I'm also open to other non-underscore methods if they are faster/better.

I also tried this:

 for (var i = 0, l = collection_var.length; i < l; i++) {
            console.log(collection_var[i]);
 }

but that's not giving me what I want either.

like image 735
streetlight Avatar asked Apr 15 '13 12:04

streetlight


People also ask

Does anyone use Backbone JS?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is a model backbone?

Model. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.


1 Answers

First method: use the models property of your collection:

var myModel
for(var i=0; i<myCollection.length; i++) {
  myModel = myCollection.models[i];
}

Second method is with the each method:

myCollection.each(function(model, index, [context]) {...});
like image 165
Loamhoof Avatar answered Oct 01 '22 14:10

Loamhoof