如何从backbone.js中的模型中获取数组元素
我有以下代码:
Person = new Backbone.Model({ data:[ { age: "27" }, {name: "alamin"} ] });
现在,我怎样才能获得价值?
person=new Person(); person.get(?);
请给我一个解决方案。
如果您使用的是此型号:
Person = new Backbone.Model({ data:[ { age: "27" }, {name: "alamin"} ] });
因此,如果您想明确地从模型中的数组中提取,您应该尝试这样做:
i = new App.Model.Person(); i.fetch(); i.get("data")[0].age;
这将返回:
27
从那里你可以根据自己的喜好迭代数据。
在定义模型时我不知道数据属性 – 也许你的意思是默认值? 如在
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]
要将数组作为对象:
使用person.get('data')
要从数组中获取属性的值:
使用person.get('data').name
或者person.get('data')['name']
要获取数组的特定元素的属性:
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.