Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 无法从对象中检索名称属性_Backbone.js - Fatal编程技术网

Backbone.js 无法从对象中检索名称属性

Backbone.js 无法从对象中检索名称属性,backbone.js,Backbone.js,从主干文档 getmodel.get(attribute) Get the current value of an attribute from the model. For example: note.get("title") 我在Rails应用程序中植入了一些包含每个国家名称的数据 Country.create!(name: "Brazil") Country.create!(name: "France") Country.create!(name: "Germany") Country

从主干文档

getmodel.get(attribute) 
Get the current value of an attribute from the model. For example: note.get("title")
我在Rails应用程序中植入了一些包含每个国家名称的数据

Country.create!(name: "Brazil")
Country.create!(name: "France")
Country.create!(name: "Germany")
Country.create!(name: "Spain")
在控制台中,我创建了一个新集合并获取了数据

countries.fetch();
Object
XHR finished loading: "http://localhost:3000/countries". 
检查长度。等于我创建的四个国家

countries.length
4
使用下划线的洗牌方法随机选择一个

c = countries.shuffle()[0]
对象有一个名称

  Backbone.Model
_changes: Array[2]
_currentAttributes: Object
_events: Object
_hasComputed: false
_previousAttributes: Object
attributes: Object
  country: Object
   created_at: "2013-01-07T06:09:43Z"
   id: 2
   name: "France"
   updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
__proto__: Object
尝试通过几种不同的方式从对象获取name属性,但均未成功

c.get('name')
undefined
c.get("name");
undefined
c.get("name")
undefined
谁能想到我可能做错了什么

我发现不寻常的一件事是,有一个“国家”属性包裹着其他属性

attributes: Object
      country: Object
       created_at: "2013-01-07T06:09:43Z"
       id: 2
       name: "France"
       updated_at: "2013-01-07T06:09:43Z"
我不知道为什么“国家”要包装其他数据。是因为我用国家模型创建了种子数据吗

Country.create!(name: "Brazil")
无论如何,
obj.get('country')
不会返回undefined

c = countries.shuffle()[0]
k = c.get('country')
Object
 created_at: "2013-01-07T06:09:43Z"
 id: 3
 name: "Germany"
 updated_at: "2013-01-07T06:09:43Z"
 __proto__: Object
但是在那之后,我不能再做一次关于这个名字的采访(也就是说,在我登上国家队之后)

是否有办法删除国家/地区包装,只需获取创建它时使用的属性?

覆盖以提取
country
元素。主干调用
parse
,然后从获取的数据填充模型:

var Country = Backbone.Model.extend({
  parse: function(attributes) {
    return attributes.country;
  }
});

这是可行的,但如果您不为集合声明模型会发生什么,我认为您不需要这样做。这是新的东西吗?我不记得看到过(例如,在主干上的Railscast中没有采取这一步)谢谢,把它放到了ActiveRecord::Base.include_root_in_json=false中
var Country = Backbone.Model.extend({
  parse: function(attributes) {
    return attributes.country;
  }
});