Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get array element from model in backbone.js

I have the following code:

Person = new Backbone.Model({
 data:[
    { age: "27" },
    {name: "alamin"}
]
});

now, how can I get the value?

person=new Person();
person.get(?);

Please provide me with a solution.

like image 746
programming lover Avatar asked Jan 27 '26 08:01

programming lover


2 Answers

If you're using this model:

Person = new Backbone.Model({

data:[
    { age: "27" },
    {name: "alamin"}
]

});

So if you want to pull from an array within a model explicitly you should try this:

i = new App.Model.Person();
i.fetch();
i.get("data")[0].age;

This would return:

27

From there you can iterate through the data however you prefer.

like image 90
Carlos Avatar answered Jan 29 '26 21:01

Carlos


I don't know of a data property when defining a model - maybe you mean defaults? as in

var Person = Backbone.Model.extend({
   defaults: {
      property1: value1,
      property2: value2,
      property3: ["arrval1", "arrval2", "arrval3"]
   });

You would retrieve the value of certain property using get: myperson.get('property1'). To set the value of a property use set: myperson.set('property1', 'newValueOfProperty')

If a property is an array the myperson.get('property3')[ index ]

like image 39
Ando Avatar answered Jan 29 '26 20:01

Ando