问题描述
有谁知道驼峰属性最近是否有问题.
does anyone know if there is a recent problem with camelcased properties.
我有一个这样的模型:
var attr = DS.attr;
App.Users = DS.Model.extend({
firstName: attr('string'),
phone: attr('string'),
email: attr('string')
});
在我的模板中,电子邮件和电话显示正确,但名字没有出现.我检查了 json 文件,一切似乎都很好.我所有的其他型号都出现了同样的问题,所以我想它必须对camelCase做些什么.
In my template email and phone show up correctly but firstName doesnt appear. I checked the json file and everything seems to be fine. With all my other models the same problems appear,so i guess it has to do something with the camelCase.
推荐答案
弃用通知:这个答案是从 2013 年开始的,直到现在还没有被修改.这不反映 JSON API 适配器,而是反映 Ember-Data 的 RESTAdapter.
Ember.js 依赖于命名约定,并且它期望多字驼峰大小写(例如 firstName
)模型属性映射到多字下划线分隔的小写属性(例如 first_name
)在 JSON 响应上.如果您的 JSON 为您提供 firstName
,或在您不控制后端 API 的情况下此约定中没有的任何内容,您可以选择定义一个 map
告诉您的适配器在 JSON 响应中查找特定键并将其映射到给定模型中的属性.
Ember.js relies on naming conventions, and it expects that multiple-word-camel-case (e.g. firstName
) model properties to be mapped to multiple-word-underscore-separated-lower-case attributes (e.g. first_name
) on the JSON response. If your JSON is giving you firstName
, or anything that is not in this convention in a scenario that you do not control the backend API, you have the option of defining a map
which tells your adapter to look for a specific key in the JSON response and map it to a property in a given Model.
你可以这样做:
DS.RESTAdapter.map('App.User', {
firstName: { key: 'firstName' },
lastName: { key: 'familyName' }
});
请注意,在上面的示例中,我添加了一个 lastName
属性,它不是您自己模型的一部分.我这样做只是为了说明您可以同时映射多个属性,并且它在 JSON 响应中的名称可以是任何内容,不一定是不同大小写中的相同名称.
Note that in the sample above I've added a lastName
property which is not part of your own model. I've done that just to make it clear that you can map several properties at the same time, and its name in the JSON response can be anything, not necessarily the same name in a different casing.
这篇关于驼峰式模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!