如何从backbone.js中的模型中获取数组元素

时间:2012-07-17 11:43:56

标签: javascript jquery backbone.js

我有以下代码:

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

现在,我怎样才能获得价值?

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

请给我一个解决方案。

4 个答案:

答案 0 :(得分:2)

如果您使用的是此型号:

Person = new Backbone.Model({

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

});

因此,如果您想明确地从模型中的数组中提取,请尝试以下方法:

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

这将返回:

27

从那里你可以根据自己的喜好迭代数据。

答案 1 :(得分:1)

在定义模型时我不知道数据属性 - 也许你的意思是默认值?如在

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

您可以使用get检索某些属性的值:myperson.get('property1')。 要设置属性的值,请使用set:myperson.set('property1','newValueOfProperty')

如果属性是数组myperson.get('property3')[index]

答案 2 :(得分:0)

将数组作为对象:

使用person.get('data')

从数组中获取属性的值:

使用person.get('data').name

person.get('data')['name']

答案 3 :(得分:0)

获取数组特定元素的属性:

var people = person.get('data'); // This gets the array of people.
var individual = people[0];      // This gets the 0th element of the array.
var age = individual.age;        // This gets the age property.
var name = individual.name;      // This gets the name property.