简体   繁体   中英

iterating over collection in backbone.js

var User = Backbone.Model.extend({
  defaults : { 
    "students" : [ 
    {   
      name : "abc",
      grade: "A",
      school: "xyz"
     }], 
     "interest":
     {   
       music : "yes"
     }   
    }   
});

var UserList = Backbone.Collection.extend({  
  model : User,
});

var obj = new UserList({"students" : [{name:"Rax", grade: "B", school : "javiers"}, {name:"John", grade: "C", school : "loreto"}], "interest" : {music: "yes"}});

for(var i = 0; i < obj.students.length; i++) {
  console.log(obj.students.at(i).get("name"));
  console.log(obj.students.at(i).get("grade"));
  console.log(obj.students.at(i).get("school"));
}

//i want to iterate over each students detail(name, grade and school) ..but this is giving me error " obj.students is undefined " ..why this error is coming?

First of all, there are several syntax errors, so look into console and fix these. Also, something is conceptually wrong with the object you pass to collection.

Collection is a "user list", the model is one user. So, perhaps, you should change the defaults data description. It doesn't make sense to make students an array for a user.

Also, when you create an instance of Collection, you then create a model by using create method , and not by just passing in the hash. You could instatinate the Model that way, but not the Collection.

So when you want to create a user, you pass only one "student" in, perhaps something like this (you also have to put "url" key in your Collection, otherwise it won't work):

var User = Backbone.Model.extend({
    defaults : { 
      "students" : [{   
        name : "abc",
        grade: "A",
        school: "xyz"
       }], 
       "interest":{   
         music : "yes"
       }   
    }
  });

  var UserList = Backbone.Collection.extend({  
    model : User,
    // `url` is required, otherwise Backbone will throw an error
    url : '/something'
  });
  var userList = new UserList();

  var bob = userList.create({
    students : [ { 
      name:'bob', 
      grade : 'a', 
      school : '123'
     } ],
    interest : { music : 'no' }
  });

  console.log( bob.get('students')[0].grade );

http://jsbin.com/elusey – here, hit "edit" and take a look at the code and in the console. You should see "a" as an output.

You could actually simplify the model to this (as I told, the data structure described above doesn't really make sense for a single user):

var User = Backbone.Model.extend({
    defaults : {   
        name : "abc",
        grade : "A",
        school : "xyz"
        interests : ["music"]
    }
});

UPD . Actually, you don't have to use create collection method in order to add models to your collection. When you create an instance of your collection you can pass in an array of models, something like this (note the difference, in your code you pass an object to a collection, but you actually need to pass an array, even if with one object in it):

var userList = new UserList([{
    name:'bob', 
    grade : 'A', 
    school : '123',
    interests : [ "music" ]
  },{
    name:'george', 
    grade : 'B', 
    school : '321',
    interests : [ "drugs" ]
  }]);

You can find the working example that is using this way of adding models (don't forget to look into console) here: http://jsbin.com/elusey/2/edit

Are you sure a user 'has many' students? That doesn't make much sense. However, if that is the case, you should add a definition for a student model and collection of students. Than, your user model should contain a student collection, and some logic in the set() method to transform an array of students to a students collection. If you want to handle collections/models nested under a model more gracefully, take a look at Backbone-relational .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM