admin管理员组文章数量:1414614
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.
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.
Share Improve this question edited Feb 13, 2017 at 13:03 Penguin9 48113 silver badges23 bronze badges asked Jul 17, 2012 at 11:43 programming loverprogramming lover 431 silver badge4 bronze badges 2- Models are supposed to contain scalar data – Esailija Commented Jul 17, 2012 at 11:46
-
I'm pretty sure you should be using Backbone.Model.extend and maybe you mean
defaults
rather than data, as you have given it initial values. – Dan Prince Commented Jul 17, 2012 at 11:54
4 Answers
Reset to default 3If 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.
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 ]
To get the array as an object:
Use person.get('data')
To get the value of an attribute from the array:
Use person.get('data').name
Or person.get('data')['name']
To obtain attributes of a specific element of the array:
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.
本文标签: javascripthow to get array element from model in backbonejsStack Overflow
版权声明:本文标题:javascript - how to get array element from model in backbone.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745151460a2644939.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论